|
Hi,
I am using wpf C# to develop a project , in this i need following..
1) add formatted text on canvas
2) resize text portion between thumbs (no need to resize whole text)
3) edit text by mouse double clicking (Show cursor to enter text.)
any control support the above three options in wpf? How can i do this ?please help me soon with a solution..
modified 9-May-12 0:03am.
|
|
|
|
|
Take a look at the richtextbox.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi, I try to import data from an Excel file and display it in a datagrid, the data are email addresses. i want that data will be shown on
<DataGridTemplateColumn Header="Adress" Width="500" IsReadOnly="True">
but when i click on boutton, another DataGridColumn appears with data, but i want that data shown on DataGridColumn="Adress"
code of parse:
public class ExcelParser
{
public DataTable GetDataTableExcel(string datasource)
{
OleDbConnection theConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" + datasource + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;\"");
theConnection.Open();
OleDbDataAdapter theDataAdapter = new OleDbDataAdapter("SELECT * FROM [Feuil1$]", theConnection);
DataTable dt = new DataTable();
theDataAdapter.Fill(dt);
return dt;
}
xaml:
<DataGrid HeadersVisibility="Column" AutoGenerateColumns="True" Height="296" HorizontalAlignment="Left" Margin="23,8,0,0" Name="dgvreceipient" VerticalAlignment="Top" Width="582" MinRowHeight="30" MinWidth="0" DataContext="{StaticResource {x:Static SystemColors.ActiveCaptionBrushKey}}" MinColumnWidth="100" SelectedValuePath="id" ItemsSource="{Binding Customers}" AlternatingRowBackground="Gainsboro" AlternationCount="2">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Adress" Width="500" IsReadOnly="True">
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Validate" Width="200" IsReadOnly="True">
</DataGridTemplateColumn>
</DataGrid.Columns>
boutton click excel
code behined:
private void btnExcel_Click(object sender, RoutedEventArgs e)
{
wpfOpenfiledialog o = new wpfOpenfiledialog();
o.openfich(1);
datasource = o.filename;
ExcelParser exc = new ExcelParser();
DataTable dt = exc.GetDataTableExcel(datasource);
}
|
|
|
|
|
Your view binding is to Customers
Then you assign the resulting dataset! to the datagrid directly - the data should be put into Customers not the control
Check the content of the datatable after it has loaded and make sure the columns are all what you expected. Then put the rows into the customer container, presuming it is an observablecollection
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
The issue is that you are setting the AutoGenerateColumns property of the DataGrid to true, which will generate it's own columns (one for each field in the datatable) as well as show your template columns (which are not bound to anything by the way, so will not display any results). You have 2 options here:-
1. Forget about your template columns, and leave AutoGenerateColumns on. Then in your SQL query you should only select the columns you want displayed, and use aliases to get the correct headers for your columns i.e.
SELECT name AS Name, emailaddress AS Address FROM youtable . This will give you the results you want except for column width.
2. Turn AutoGenerateColumns off in your DataGrid, and the use the DisplayMemberBinding property of your template columns to bind the column to the datatable field i.e
<DataGridTemplateColumn Header="Adress" DisplayMemnerBinding={Binding Path=emailaddress} Width="500" IsReadOnly="True"> . This will also get you your desired result with column widths.
Personally I never use DataTables to bind to WPF controls, preferring to have a class that holds my object properties, and then having an ObservableCollection of that class that holds all instances of that class to bind to the DataGrid.
Hope this helps
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
thnk you, please I tried to use interface: this is the code but it doesn't work
public interface Iimportdata
{
DataView GridData { get; set; }
}
private DataView Data = null;
public DataView GridData
{
get
{ return Data;
}
set
{
Data = value;
NotifyPropertyChanged("GridData");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private void btnExcel_Click(object sender, RoutedEventArgs e)
{
ExcelParser exc = new ExcelParser();
DataTable dt = exc.GetDataTableExcel(datasource);
Iimportdata imp = Window.GetWindow(this) as Iimportdata;
imp.GridData = dt.DefaultView;
gbReceipient.Visibility = Visibility.Visible;
btnValidate.Visibility = Visibility.Visible;
}
XAML:
<DataGridTemplateColumn Header="Adress" Width="100" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=GridData}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
|
|
|
|
|
Hello Everyone
I did asked a question to my problem couple of days ago on: How can I display all the details of the employee in the textboxes, comboboxes, and checkbox when I click on the cell of the DataGrid?
Well somehow I managed to solve my problem with the help on searching on the internet, but I'm facing another problem.
When I run my application I'm displaying only the names of the employee from the database on the DataGrid, then when I click on DataGrid cell (of the employee name, to display all the details of that employee into textboxes, comboboxes, and checkbox) some-how it repeats the details of the employee into textboxes.
To be more clear to my problem:
In my database table (EmployeeDetails table) I have 2 employee record details,
These 2 employees (their names will be displayed on the DataGrid)
When I click on the first employee name on the DataGrid cell to display his/her details
When I click on the second employee name on the DataGrid cell to display his/her details etc. etc...
Could someone please view the code I provided below and tell me what am I doing wrong...
DataGrid xaml code:
<DataGrid Height="490" HorizontalAlignment="Left" Margin="6,8,0,0" Name="GridViewEmployeeName" VerticalAlignment="Top" Width="200" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" Background="{x:Null}" FontFamily="Verdana" FontWeight="Bold" FontSize="16" GridLinesVisibility="None" BorderBrush="Silver" RowDetailsVisibilityMode="Visible" CanUserResizeRows="False" ItemsSource="{Binding}" SelectionChanged="GridViewEmployeeName_SelectionChanged" SelectionMode="Single" IsSynchronizedWithCurrentItem="{x:Null}" CanUserResizeColumns="False" AutoGenerateColumns="False" HeadersVisibility="Column" EnableRowVirtualization="False" CanUserAddRows="False" RowHeight="22">
<DataGrid.Columns>
<DataGridTextColumn FontSize="12" FontWeight="Bold" Header="Employee Name" IsReadOnly="True" Width="200" Binding="{Binding Name}" CanUserResize="False" FontFamily="Verdana" />
</DataGrid.Columns>
</DataGrid>
C# code Window Load displaying only names of the employee in DataGrid
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (OleDbConnection conn = new OleDbConnection(ConString))
{
CmdString = "SELECT Name FROM EmployeeDetails";
OleDbCommand comm = new OleDbCommand(CmdString, conn);
OleDbDataAdapter sda = new OleDbDataAdapter(comm);
DataTable dt = new DataTable("EmployeeDetails");
sda.Fill(dt);
GridViewEmployeeName.ItemsSource = dt.DefaultView;
}
}
C# code
private void GridViewEmployeeName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string ConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\USER\Desktop\iPosSystem\iPosSystemMenu\iPosSystemMenu\DataBase\RestaurantMenu.accdb;Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(ConnStr);
string sql = "SELECT Name, NIN, Phone, Address, PostCode, City, JobTitle, AccessCode, AccessLevel, AssignTableAccess FROM EmployeeDetails";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtFullName.Text += dr["Name"].ToString();
txtNIN.Text += dr["NIN"].ToString();
txtPhoneNumber.Text += dr["Phone"].ToString();
txtAddress.Text += dr["Address"].ToString();
txtPostCode.Text += dr["PostCode"].ToString();
txtCity.Text += dr["City"].ToString();
JobTitleComboBox.Text += dr["JobTitle"].ToString();
txtAccessCode.Text += dr["AccessCode"].ToString();
AccessLevelComboBox.Text += dr["AccessLevel"].ToString();
AssignTableAccessCheckBox.IsChecked = dr["AssignTableAccess"].Equals(true);
}
dr.Close();
conn.Close();
}
}
Could someone help me on this please I'm new to WPF...
Kind Regards to everyone
Lapeci
|
|
|
|
|
i try to change the size of text in ritchbox with code behind
TextRange tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
tr.ApplyPropertyValue(FontSizeProperty, (double)9);
but i want to change
tr.ApplyPropertyValue(FontSizeProperty, (double)9) by
double size=Convert.ToDouble(comboboxfontsize.selectedItem)
tr.ApplyPropertyValue(FontSizeProperty, size)
i get an exception
Impossible d'effectuer un cast d'un objet de type 'System.Windows.Controls.ComboBoxItem' en type 'System.IConvertible'.
so how can i get the value selected item?
|
|
|
|
|
I don't know how you are populating the ComboBox, but I assume it is in the XAML. In this case the SelectedItem would be a ComboBoxItem which does not implement the IConvertible interface and so cannot be converted to a double. Personally, I would use WPF's binding mechanism to implement this using 2 properties, and ObservableCollection<int> to hold the allowed font sizes, and an int property to hold the selected font size, something like this:-
public ObservableCollection<int> Fonts
{
get
{
return new ObservableCollection<int>() { 8, 9, 10, 12, 14 };
}
}
int selectedFontSize;
public int SelectedFontSize
{
get
{
return selectedFontSize;
}
set
{
if (selectedFontSize != value)
{
selectedFontSize = value;
OnPropertyChanged("SelectedFontSize");
}
}
}
(this assumes you user control / window implements INotifyPropertyChanged ). Then you can just create the bindings in your XAML like this:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<ComboBox ItemsSource="{Binding Fonts}" SelectedItem="{Binding SelectedFontSize}" Width="200" HorizontalAlignment="Left"/>
<RichTextBox Grid.Row="1">
<FlowDocument FontSize="{Binding SelectedFontSize}">
<Paragraph >
Hello World!
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
and that is all there is to it, not forgetting to set the DataContext of your user control / window to itself like this in the constructor:
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
Hope this helps
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
Hi,
i have a wpf user control wich allow me to show print window .
how can i show wpf user control when i click on button in another window??
|
|
|
|
|
Place it in a window and display it on button click.
private void myButton_Click(object sender, EventArgs e)
{
Window myWindow = new Window
{
Content = new myUserControl()
};
window.ShowDialog();
}
|
|
|
|
|
Hello Everyone
I have this slight problem maybe someone can help me please...
I have created a WPF project on VS2010. In this project I have a window with one DataGrid (on the left side of the window), seven TextBoxes, two ComboBoxes and one CheckBox (on the right side of the window).
When I run application, on the DataGrid I display only the name of employee from the database.
My Question:
How can I display all the details of the employee in the textboxes, comboboxes, and checkbox when I click on the cell of the datagrid?
Could someone help me on this please I'm new to WPF...
Kind Regards to everyone
Lapeci
|
|
|
|
|
You could consider presenting your data in a ListBox or a ListView and set IsSyncronisedWithCurrentItem="True" using the autamatic Parent Child binding in WPF.
|
|
|
|
|
Is any way to do it with datagrid rather then with listbox, and is it possible to show me with some sample code according to my question please...
kind regards
lapeci
|
|
|
|
|
I don't know any quick way to do it with Grid, but you can get a very similar look by using a list view - maybe something along these lines: Other than that wait for some one else to come up with the answer. Or read up on Binding.
<ListView Name="lvwCommandLog"
ItemsSource="{Binding Path=CommandLog, Mode=TwoWay}"
MouseDoubleClick="lvwCommandLog_MouseDoubleClick"
ToolTip="Double click to run this command again" >
<ListView.View >
<GridView >
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name, Mode=TwoWay}" ></GridViewColumn>
<GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" ></GridViewColumn>
<GridViewColumn Header="Time" DisplayMemberBinding="{Binding Path=Time, StringFormat=\{0:h\\:mm\\:ss\}}"></GridViewColumn>
</GridView>
</ListView.View>
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Do Something" Click="MenuItem_Click" />
</ContextMenu>
</ListView.ContextMenu>
</ListView>
<Text Text="{Binding Name}"/>
|
|
|
|
|
There are two ways to do this:
1. Bind the DataGrid's SelectItem to a property in your ViewModel (or code behind if you're not using MVVM ), then in the setter for that property populate properties for the TextBoxes, ComboBoxes etc.
This method has the advantage of being able to add a Cancel button.
2. Bind the TextBoxes, ComboBoxes etc to the DataGrid's SelectedItem property. Something like this:
{Binding ElementName=DataGrid1, Path=SelectedItem.TextPropertyName}
This method saves you a bit of coding but doesn't offer an easy way to cancel changes.
|
|
|
|
|
I create a library of these classes contains a user control that contains images as background to some button, I add it to the main page such as referance, I added this code to retrieve the control xaml user
<Window x: Class = "WpfApplication3.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" width = "525"
xmlns: usercontrol = "clr-namespace: usercontrol; assembly = usercontrol">
<Grid>
<usercontrol:myeditor> </ usercontrol: myeditor>
</ Grid>
</ Window>
but i get an exception: the user control Cannot locate resource
|
|
|
|
|
What are the values of the 'Build Action' and 'Copy to Output' properties of the background image (right click - properties)?
What does the xaml (or code) look like for assigning the image as the background of the UserControl look like?
|
|
|
|
|
Your error is going to be in the myeditor usercontrol. Like Jeremy suggested check to ensure that your image sources on the control are correct, and that the control is able to locate them during runtime.
|
|
|
|
|
Hi guys,
I'm working for the first time in WPF with MVVM pattern and I have a datagrid that is populated according to search terms in textbox on top. Right now, I'm able to populate the grid with all the data but I'm not able to get the value of the TextBox so I can filter it.
So here's a bit of the code:
In ViewModel:
private string p_searchName;
public string _searchName
{
get
{
return p_searchName;
}
set
{
p_searchName = value;
base.RaisePropertyChanged("_searchName");
}
}
In xaml file
<TextBox Height="23" HorizontalAlignment="Left" Margin="2,45,0,0" Text="{Binding _searchName}"
Name="tb_SearchName" VerticalAlignment="Top" Width="99" FontFamily="Lucida Console" TabIndex="10"
Grid.Column="1" />
Any help is greatly appreciated!
Thanks
|
|
|
|
|
The binding looks right, but are there any errors in the output window when loading that form?
The other thing that it may be, is that the TextBox control doesn't update the ViewModel until it loses focus. Not sure about that though...
|
|
|
|
|
There are no errors in the output window. But you are quite right about the focus. I just added
UpdateSourceTrigger=PropertyChanged
like this
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
and it actually works... But I really don't see why this is so.
Thanks for the help!
|
|
|
|
|
I assume the default for UpdateSourceTrigger is LostFocus, and it is set that way for performance reasons. Every time you call the setter, the setter raises the OnPropertyChanged event, WPF listens to that event and calls the getter.
|
|
|
|
|
Hmm.. thanks Jeremy!
|
|
|
|
|
Make your binding Mode="TwoWay" default is only one way so you see the data but are not telling the datacontext the data has changed
And yes the change is only notified when the user leaves the textbox
Never underestimate the power of human stupidity
RAH
|
|
|
|