I have a list of custom classes that I have bound them to the RadGridView through the below code:
this.ItemsSource = CorrelationCalibraationGridInput.ListOfCalibratableCorrelationClasses;
then I have created the columns manually. For one of the columns that is check box column, I need to enable disable the check box binding to a property of class and set its check state based on another property of the class.
I used the code below but the enablity does not bind to the IsNotCalibratedYet property. Can you explain why and how can I solve it?(note that the check state is correctly binded to the IsCalibratedUSed property of the class).
GridViewDataColumn IsCalibratedUSedColumn = new GridViewDataColumn()
{
UniqueName = "IsCalibratedUSedColumn",
Header = "Use calibrated",
DataMemberBinding = new Binding("IsCalibratedUSed"),
IsFilterable = false,
};
Binding enablityBinding = new Binding("IsNotCalibratedYet");
enablityBinding.Mode= BindingMode.OneWay;
enablityBinding.UpdateSourceTrigger= UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(IsCalibratedUSedColumn, GridViewDataColumn.IsEnabledProperty,enablityBinding );
this.Columns.Add(IsCalibratedUSedColumn);
You should set the IsReadOnlyBinding property of the GridViewDataColumn to your Binding:
GridViewDataColumn IsCalibratedUSedColumn = new GridViewDataColumn()
{
UniqueName = "IsCalibratedUSedColumn",
Header = "Use calibrated",
DataMemberBinding = new Binding("IsCalibratedUSed"),
IsFilterable = false,
};
Binding enablityBinding = new Binding("IsNotCalibratedYet");
enablityBinding.Mode = BindingMode.OneWay;
enablityBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
IsCalibratedUSedColumn.IsReadOnlyBinding = enablityBinding;
this.Columns.Add(IsCalibratedUSedColumn);
Depending on whether your source property returns true/false you may want to use an InvertedBooleanConverter:
Binding enablityBinding = new Binding("IsNotCalibratedYet");
enablityBinding.Mode = BindingMode.OneWay;
enablityBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
enablityBinding.Converter = new InvertedBooleanConverter();
You can do this using the following setting:
public MainWindow()
{
InitializeComponent();
lv.ItemsSource = new Item[3] { new Item() { IsNotCalibratedYet=true }, new Item() { IsNotCalibratedYet = false }, new Item() { IsNotCalibratedYet = true } };
gv.Columns.Add(new GridViewColumn()
{
DisplayMemberBinding = new Binding("IsNotCalibratedYet"),
});
}
in which:
public class Item
{
public bool IsNotCalibratedYet { get; set; }
}
and Xaml is
<ListView Name="lv" >
<ListView.View>
<GridView x:Name="gv" AllowsColumnReorder="true"
ColumnHeaderToolTip="Employee Information">
</GridView>
</ListView.View>
</ListView>
Related
To follow my previous post here => Binding SelectedItem of ComboBox in DataGrid with different type
I have now a datagrid containing 2 columns, one with a text, the other with a combobox (in a datatemplate, written thru the C# code, not the Xaml).
After having done some choice on the combobox, I now would like to parse the result but the value of the cell containing my combobox stay empty :
foreach(DataRowView row in Datagrid1.Items)
{
var firstColumNresult = row.Row.ItemArray[0];// Return correctly a string
var myrow = row.Row.ItemArray[1];// always empty...
}
The result is that I cant get the values of my (previously generated) combobox.
I suppose one binding must missed somewhere...
This is the combobox creation code :
DataTable tableForDG = new DataTable();
tableForDG.Columns.Add(new DataColumn { ColumnName = "Name", Caption = "Name" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "Attachment", Caption = "Attachment" }); // this column will be replaced
tableForDG.Columns.Add(new DataColumn { ColumnName = "AttachmentValue", Caption = "AttachmentValue" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "DisplayCombo", Caption = "DisplayCombo", DataType=bool });
// Populate dataview
DataView myDataview = new DataView(tableForDG);
foreach (var value in listResults)// a list of string
{
DataRowView drv = myDataview.AddNew();
drv["Name"] = value.Name;
drv["Attachment"] = value.Name;// this column will be replaced...
drv["DisplayCombo"] = true;// but it can be false on my code...
}
var DG = myDataview;//
Datagrid1.ItemsSource = DG;
Datagrid1.AutoGenerateColumns = true;
Datagrid1.Items.Refresh();
DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
dgTemplateColumn.Header = "Attachment";
var newCombobox = new FrameworkElementFactory(typeof(ComboBox));
newCombobox.SetValue(ComboBox.NameProperty, "myCBB");
Binding enableBinding = new Binding();
newCombobox.SetValue(ComboBox.IsEnabledProperty, new Binding("DisplayCombo"));
newCombobox.SetValue(ComboBox.SelectedValueProperty, new Binding("AttachmentValue"));
List<string> listUnitAlreadyAttached = new List<string>();
// fill the list...
enableBinding.Source = listUnitAlreadyAttached;
newCombobox.SetBinding(ComboBox.ItemsSourceProperty, enableBinding);
var dataTplT = new DataTemplate();
dataTplT.VisualTree = newCombobox;
dgTemplateColumn.CellTemplate = dataTplT;
Datagrid1.Columns[1] = dgTemplateColumn;
Any idea/advice ?
You should explicitely specify the binding mode and update trigger of your binding. Also use SetBinding instead of SetValue:
var valueBinding = new Binding("AttachmentValue")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
newCombobox.SetBinding(ComboBox.SelectedValueProperty, valueBinding);
This should enable you to get the selected value into your row data. It might not update in the displayed datagrid value for the AttachmentValue column.
I have a list view in which each row contains 5 entries. The list box looks like this:
I need to store (display) the name of variable and the value present in "Physical value" column text box when i press OK button. For e.g. if i enter 45 in the physical value text box (only one row at a time) then the name of the variable and value "45" should be stored (displayed). I am able to retrieve the name of the variables but not the value of the text box.
My try:
This code will populate the list view with variables and bind it to the properties.
public void Populatevariables(IList<string> variables)
{
int rowcount = 0;
dataGrid.RowDefinitions.Clear();
dataGrid.ColumnDefinitions.Clear();
RowDefinition rd = new RowDefinition();
rd.Height = new GridLength();
dataGrid.RowDefinitions.Add(rd);
dataGrid.RowDefinitions.Add(new RowDefinition());
dataGrid.ColumnDefinitions.Add(new ColumnDefinition());
Label t1 = new Label();
t1.Content = "Variables";
Grid.SetColumn(t1, 0);
Grid.SetRow(t1, rowcount);
dataGrid.Children.Add(t1);
ListView VrblPopulateList = new ListView();
GridView g1 = new GridView();
g1.AllowsColumnReorder = true;
//l1.View = g1;
GridViewColumn g2 = new GridViewColumn();
g2.Header = "Name";
g2.Width = 200;
g2.DisplayMemberBinding = new Binding("Name");
g1.Columns.Add(g2);
GridViewColumn g5 = new GridViewColumn();
g5.Header = "DataType";
g5.Width = 200;
g5.DisplayMemberBinding = new Binding("DataType");
g1.Columns.Add(g5);
GridViewColumn g3 = new GridViewColumn();
g3.Header = "Current Value";
g3.Width = 200;
DataTemplate dt1 = new DataTemplate();
FrameworkElementFactory FF1 = new FrameworkElementFactory(typeof(TextBox));
FF1.SetBinding(TextBox.BindingGroupProperty, new Binding("Current_Value"));
FF1.SetValue(FrameworkElement.HeightProperty, Height = 30);
FF1.SetValue(FrameworkElement.WidthProperty, Width = 150);
dt1.VisualTree = FF1;
g3.CellTemplate = dt1;
g1.Columns.Add(g3);
GridViewColumn g6 = new GridViewColumn();
g6.Header = "Physical Value";
g6.Width = 200;
DataTemplate dt2 = new DataTemplate();
FrameworkElementFactory FF2 = new FrameworkElementFactory(typeof(TextBox));
FF2.SetBinding(TextBox.BindingGroupProperty, new Binding("Physical_Value"));
//FF2.AddHandler(TextBox.TextChangedEvent, txtchanged, true);
FF2.SetValue(FrameworkElement.HeightProperty, Height = 30);
FF2.SetValue(FrameworkElement.WidthProperty, Width = 150);
dt2.VisualTree = FF2;
g6.CellTemplate = dt2;
g1.Columns.Add(g6);
GridViewColumn g4 = new GridViewColumn();
g4.Header = "Action";
g4.Width = 200;
DataTemplate dt = new DataTemplate();
FrameworkElementFactory FF = new FrameworkElementFactory(typeof(Button));
FF.SetBinding(Button.BindingGroupProperty, new Binding("ToDo"));
FF.SetValue(FrameworkElement.HeightProperty,Height = 30);
FF.SetValue(FrameworkElement.WidthProperty, Width = 150);
FF.SetValue(System.Windows.Controls.Button.ContentProperty,"OK");
FF.AddHandler(Button.ClickEvent, new RoutedEventHandler(b1_click));
dt.VisualTree = FF;
g4.CellTemplate = dt;
g1.Columns.Add(g4);
VrblPopulateList.View = g1;
Grid.SetRow(VrblPopulateList, rowcount + 1);
dataGrid.Children.Add(VrblPopulateList);
for (int i = 0; i < variables.Count; i++)
{
Label lb1 = new Label();
lb1.Content = variables[i].Name;
Label lb2 = new Label();
lb2.Name = variables[i].datatype;
DataTemplate dd = new DataTemplate();
TextBox tb = new TextBox();
tb.Name = "TextBox" + i.ToString();
Button b1 = new Button();
VrblPopulateList.Items.Add(new User() { Name = lb1.Content, DataType = lb2.Name, Current_Value = tb, Physical_Value = tb, ToDo = b1 });
}
}
This code defines the property which is bind while populating:
public class User
{
public object Name { get; set; }
public string DataType { get; set; }
public Control Current_Value
{
get;
set;
}
public Control Physical_Value
{
get;
set;
}
public Control ToDo { get; set; }
}
At last this code will retrieve all the items when button is clicked.
private void b1_click(object sender, RoutedEventArgs e)
{
User item = (User)((Button)sender).DataContext;
TextBox t = (TextBox)item.Physical_Value;
MessageBox.Show(item.Name.ToString() + t.Text);
}
The text box value is always empty. I know it can be solved by adding handler to "text changed" event while populating. But i dont know how to do it. Please help.
As mentioned in the comment by #Ponas Justas i have to do following changes in my code:
Set the UpdateSourceTrigger property of the text box.
Change the user model accordingly.
After doing above changes my code looks like:
FF2.SetBinding(TextBox.BindingGroupProperty, new Binding("Physical_Value"));
FF2.SetBinding(TextBox.TextProperty, new Binding("PhysicalValueTxtChanged") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
User Model
public class User
{
public object Name { get; set; }
public string DataType { get; set; }
public Control Current_Value
{
get;
set;
}
public string _PhysicalValueTxtChanged = null;
public string PhysicalValueTxtChanged
{
get { return _PhysicalValueTxtChanged; }
set
{
_PhysicalValueTxtChanged = value;
}
}
public Control ToDo { get; set; }
}
After doing that the text in the text box can be easily stored by just modifying like this:
private void b1_click(object sender, RoutedEventArgs e)
{
User item = (User)((Button)sender).DataContext;
string txt = item.PhysicalValueTxtChanged;
MessageBox.Show(item.Name.ToString() + txt);
}
Thanks a lot Ponas Justas.
I'm working on a cookbook for myself, written in WPF/C#.
Additionally I'm new to Data Bindings.
My Problem is, I want to generate a Datagrid in a TabItem on runtime in code behind, including Bindings. I can't set a Datagrid at XAML because I want to create all TabItems dynamically.
Following Code so far:
XAML:
<UniformGrid Columns="2" Rows="1">
<TabControl Name="TabControl" TabStripPlacement="Left"/>
<TabItem Header= "first dish" Name = "firstdish"/>
</UniformGrid>
XAML.cs for generation:
//New Grid
var Grid = new DataGrid();
//Start Test list creation with three items
var TestList = new List<Receipt>();
//Set binding
Grid.ItemsSource = TestList;
var Rec = new Receipt();
Rec.Creator = "DaJohn1";
Rec.ID = 1;
Rec.Title = "TestReceipt1";
var Rec2 = new Receipt();
Rec2.Creator = "DaJohn2";
Rec2.ID = 2;
Rec2.Title = "TestReceipt2";
var Rec3 = new Receipt();
Rec3.Creator = "DaJohn3";
Rec3.ID = 3;
Rec3.Title = "TestReceipt3";
TestList.Add(Rec);
TestList.Add(Rec2);
TestList.Add(Rec3);
//End Test list creation
//Add Column
var SingleColumn = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn);
SingleColumn.Binding = new Binding("Creator");
SingleColumn.Header = "Creator";
//Add Column
var SingleColumn2 = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn2);
SingleColumn2.Binding = new Binding("Title");
SingleColumn2.Header = "Title";
//Set tabitem content to datagrid
firstdish.Content = Grid;
All I'm getting is an datagrid with four rows (looks like the count of Items is right), which are all empty, no data to be seen.
I'm staring at this since last Weeks Monday and can't find an answer anywhere.
Thanks for any ideas and solutions.
try changing
var TestList = new List<Receipt>();
to
var TestList = new ObservableCollection<Receipt>();
as it automatically notifies UI about changes.
I had a similar problem with items not rendering so this may be it.
I've taken your code and checked some of the things you do: The main error is that in your xaml code you created the Tab Control and then Put the TabItem outside it, Tabitem must be inside the control for it to work correctly. so First error is:
<TabControl Name="TabControl" TabStripPlacement="Left">
<TabItem Header="First dish" Name = "firstdish" />
</TbControl>
Other things you need to do before going on in my opinion are:
Assign your window or other UI element itself as datacontext
Verify that your Receipt class implements the INotifyPropertyChanged event that has to be raised by all its properties, or implement your properties as DependencyProperties (even if the latter is not necessary)
Transform your datasource TestList in an ObservableCollection
Create TestList as a class property not a local variable so that it is into the datacontext
I've made a small sample using the above indication and your code to let you see better how that works. You can download the zip here:
TestClassDataGrid.zip
Below code should work for you,
XAML:
<TabControl Name="TabControl" TabStripPlacement="Left">
<TabItem Header= "first dish" Name = "firstdish"/>
</TabControl>
.cs file
public Window()
{
InitializeComponent();
var Grid = new DataGrid();
//Start Test list creation with three items
var TestList = new List<Receipt>();
//Set binding
Grid.ItemsSource = TestList;
var Rec = new Receipt();
Rec.Creator = "DaJohn1";
Rec.ID = 1;
Rec.Title = "TestReceipt1";
var Rec2 = new Receipt();
Rec2.Creator = "DaJohn2";
Rec2.ID = 2;
Rec2.Title = "TestReceipt2";
var Rec3 = new Receipt();
Rec3.Creator = "DaJohn3";
Rec3.ID = 3;
Rec3.Title = "TestReceipt3";
TestList.Add(Rec);
TestList.Add(Rec2);
TestList.Add(Rec3);
//End Test list creation
//Add Column
var SingleColumn = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn);
SingleColumn.Binding = new Binding("Creator");
SingleColumn.Header = "Creator";
//Add Column
var SingleColumn2 = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn2);
SingleColumn2.Binding = new Binding("Title");
SingleColumn2.Header = "Title";
//Set tabitem content to datagrid
Grid.AutoGenerateColumns = false;
firstdish.Content = Grid;
}
Why is this code-behind DataBinding not working, when I do the same thing in XAML it is working fine.
Binding frameBinding = new Binding();
frameBinding.Source = mainWindowViewModel.PageName;
frameBinding.Converter = this; // of type IValueConverter
frameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
frameBinding.IsAsync = true;
frame.SetBinding(Frame.ContentProperty, frameBinding);
You have only set the Source of the Binding, but not its Path. The declaration should look like this, using the mainWindowViewModel instance as Source:
Binding frameBinding = new Binding();
frameBinding.Path = new PropertyPath("PageName"); // here
frameBinding.Source = mainWindowViewModel; // and here
frameBinding.Converter = this;
frameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
frameBinding.IsAsync = true;
frame.SetBinding(Frame.ContentProperty, frameBinding);
or shorter:
Binding frameBinding = new Binding
{
Path = new PropertyPath("PageName"),
Source = mainWindowViewModel,
Converter = this,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
IsAsync = true
};
frame.SetBinding(Frame.ContentProperty, frameBinding);
I have a dynamic Datagrid that I have created. I am creating each column for it through code behind. I am having troubles on a column that I want to be displayed at a textblock when not editing, but as a combobox while editing. I have an ObservableCollection of Transactions. Each Transaction has a type called "Account". Here is what I have so far:
private DataGridTemplateColumn GetAccountColumn()
{
// Create The Column
DataGridTemplateColumn accountColumn = new DataGridTemplateColumn();
accountColumn.Header = "Account";
Binding bind = new Binding("Account");
bind.Mode = BindingMode.TwoWay;
// Create the TextBlock
FrameworkElementFactory textFactory = new FrameworkElementFactory(typeof(TextBlock));
textFactory.SetBinding(TextBlock.TextProperty, bind);
DataTemplate textTemplate = new DataTemplate();
textTemplate.VisualTree = textFactory;
// Create the ComboBox
bind.Mode = BindingMode.OneWay;
FrameworkElementFactory comboFactory = new FrameworkElementFactory(typeof(ComboBox));
comboFactory.SetValue(ComboBox.DataContextProperty, this.Transactions);
comboFactory.SetValue(ComboBox.IsTextSearchEnabledProperty, true);
comboFactory.SetBinding(ComboBox.ItemsSourceProperty, bind);
DataTemplate comboTemplate = new DataTemplate();
comboTemplate.VisualTree = comboFactory;
// Set the Templates to the Column
accountColumn.CellTemplate = textTemplate;
accountColumn.CellEditingTemplate = comboTemplate;
return accountColumn;
}
The value displays in the TextBlock. However, in the combobox, I am only getting one character to display per item. For example, here is the textblock:
But when I click to edit and go into the combobox, here is what is shown:
Can someone help me out so that the items in the Combobox are displayed properly? Also, when I select something from the Combobox, the textblock isn't updated with the item I selected.
UPDATED:
Here is my column as of now. The items in the ComboBox are being displayed properly. The issue now is that when a new item is selected, the text in the TextBlock isn't updated with the new item.
private DataGridTemplateColumn GetAccountColumn()
{
// Create The Column
DataGridTemplateColumn accountColumn = new DataGridTemplateColumn();
accountColumn.Header = "Account";
Binding bind = new Binding("Account");
bind.Mode = BindingMode.OneWay;
// Create the TextBlock
FrameworkElementFactory textFactory = new FrameworkElementFactory(typeof(TextBlock));
textFactory.SetBinding(TextBlock.TextProperty, bind);
DataTemplate textTemplate = new DataTemplate();
textTemplate.VisualTree = textFactory;
// Create the ComboBox
Binding comboBind = new Binding("Account");
comboBind.Mode = BindingMode.OneWay;
FrameworkElementFactory comboFactory = new FrameworkElementFactory(typeof(ComboBox));
comboFactory.SetValue(ComboBox.IsTextSearchEnabledProperty, true);
comboFactory.SetValue(ComboBox.ItemsSourceProperty, this.Accounts);
comboFactory.SetBinding(ComboBox.SelectedItemProperty, comboBind);
DataTemplate comboTemplate = new DataTemplate();
comboTemplate.VisualTree = comboFactory;
// Set the Templates to the Column
accountColumn.CellTemplate = textTemplate;
accountColumn.CellEditingTemplate = comboTemplate;
return accountColumn;
}
The "Accounts" property is declared like this in my MainWindow class:
public ObservableCollection<string> Accounts { get; set; }
public MainWindow()
{
this.Types = new ObservableCollection<string>();
this.Parents = new ObservableCollection<string>();
this.Transactions = new ObservableCollection<Transaction>();
this.Accounts = new ObservableCollection<string>();
OpenDatabase();
InitializeComponent();
}
Here is my Transaction Class:
public class Transaction
{
private string date;
private string number;
private string account;
public string Date
{
get { return date; }
set { date = value; }
}
public string Number
{
get { return number; }
set { number = value; }
}
public string Account
{
get { return account; }
set { account = value; }
}
}
You bind the ItemsSource to the selected value, a string, aka char array, so every character is used as an item, the ItemsSource binding presumably should target some other collection from which the value can be chosen.
Dim newBind As Binding = New Binding("LinktoCommonOutputBus")
newBind.Mode = BindingMode.OneWay
factory1.SetValue(ComboBox.ItemsSourceProperty, dictionary)
factory1.SetValue(ComboBox.NameProperty, name)
factory1.SetValue(ComboBox.SelectedValuePathProperty, "Key")
factory1.SetValue(ComboBox.DisplayMemberPathProperty, "Value")
factory1.SetBinding(ComboBox.SelectedValueProperty, newBind)
By creating Binding you can set SelectedValue in a datagrid for WPF.