I dynamically create a DataGridComboboxColum in the code. This works fine, however when I select an item in the Combobox in the Grid it disappears after i leave the combobox.
Here is the code:
MyDataGrid.ItemsSource = ergList;
DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
cb.ItemsSource = data
cb.Header = "Tag";
cb.DisplayMemberPath = "Tag";
MyDataGrid.Columns.Add(cb);
How can i fix this?
You need to bind the selected value in the ComboBox to a property of the item in your ergList:
MyDataGrid.ItemsSource = ergList;
DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
cb.ItemsSource = data
b.Header = "Tag";
cb.DisplayMemberPath = "Tag";
cb.SelectedValueBinding = new Binding("SomePropertyOfAnItemInErgList");
MyDataGrid.Columns.Add(cb);
Make sure that the types of the items in the ComboBox and the property to hold the selected value match.
Related
I'm having trouble binding values to dynamically created controls. When a user loads a custom file and that file will have a unknown number of arguments. Arguments have a Group property that when grouped will dynamically add tabItems to a tabControl. I then loop through the arguments and add a label and, for now, a textbox to a grid inside the tabs. though i intend to use different controls depending on the arument type. I want to bind the argument Value property to the textbox. The tabs, labels and textboxes are added fine but, no value binding
He if my not yet re-factored solution so far;
myTab.Items.Clear();
var args = viewModel.Arguments;
var groups = args.GroupBy(arg => arg.Groups);
foreach (var group in groups)
{
TabItemExt tab = new TabItemExt();
tab.Header = group.Key;
Grid grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition());
grid.ColumnDefinitions.Add(new ColumnDefinition());
int count = 0;
foreach (var argument in group)
{
RowDefinition newRow = new RowDefinition();
grid.RowDefinitions.Insert(count, newRow);
LabelTextBlock label = new LabelTextBlock();
label.Text = argument.DisplayName;
Grid.SetRow(label, count);
Grid.SetColumn(label, 0);
TextBox textBox = new TextBox();
var binding = new Binding();
binding.Source = viewModel.Arguments[argument.Name];
//binding.Source = argument
binding.Path = new PropertyPath("Value");
textBox.SetBinding(TextBlock.TextProperty, binding);
Grid.SetRow(textBox, count);
Grid.SetColumn(textBox, 1);
grid.Children.Add(label);
grid.Children.Add(textBox);
count += 1;
}
tab.Content = grid;
myTab.Items.Add(tab);
}
textBox.SetBinding(TextBlock.TextProperty, binding);
should have been
textBox.SetBinding(TextBox.TextProperty, binding);
just a little over dependent on intellisense.
I have a DataTable that is coming from a Web Service, which I need to bind to a ComboBox. I have not grokked doing binding in XAML yet so this question is about binding in code instead. So far I have tried
cboManager.DataContext = Slurp.DistrictManagerSelect().DefaultView;
cboManager.DisplayMemberPath = "Name";
cboManager.SelectedValuePath = "NameListId";
cboManager.SetBinding(ComboBox.ItemsSourceProperty, new Binding());
And I have tried
DataTable tbl = new DataTable();
tbl = Slurp.DistrictManagerSelect();
cboManager.ItemsSource = ((IListSource)tbl).GetList();
cboManager.DisplayMemberPath = "[Name]";
cboManager.SelectedValuePath = "[NameListId]";
DataContext = this;
In both cases I get the list of managers to show but when I select from the ComboBox I get [Name] and [NameListId] and not the values I am expecting. What am I doing wrong (other than not using XAML's DataBinding)?
Edit added after answers to my original post came in.
So (based on Rachel's response) try number three looks like this:
using (DataTable tbl = Slurp.DistrictManagerSelect())
{
List<ManagerList> list = new List<ManagerList>();
foreach (var row in tbl.Rows)
{
list.Add(new ManagerList
{
NameListId = (int)row[0],
Name = row[1].ToString()
});
}
}
Assuming I am doing what she meant the correct way I am no getting this error Cannot apply indexing with [] to an expression of type 'object'
Have you tried to just bind to the DataTable directly? Do you have columns Name and NameListId? Leave off the DataContext (you already assigned the ItemsSource).
DataTable tbl = Slurp.DistrictManagerSelect();
cboManager.ItemsSource = tbl;
cboManager.DisplayMemberPath = "Name";
cboManager.SelectedValuePath = "NameListId";
When you cast to the IListSource I suspect it is combining all the columns. If you want to bind to a list then you need to create items that have properties Name and NameListID.
I think that's because your ItemsSource is a DataTable, so each ComboBoxItem contains a DataContext of a DataRow, and the DataRow class doesn't have properties called Name or NameListId
Basically, you're trying to tell the ComboBox to display DataRow.Name, and set the value to DataRow.NameListId, both of which are not valid properties.
I usually prefer to parse data into objects, and bind the ItemsSource a List<MyObject> or ObservableCollection<MyObject>
foreach(DataRow row in tbl.Rows)
list.Add(new MyObject { Name = row[0].ToString(), NameListId = (int)row[1] });
cboManager.ItemsSource = list;
I wanted a combo box in data grid which i added using the following code behind
DataColumn dc;
DataGridNS.DataGridTemplateColumn dgc = new DataGridNS.DataGridTemplateColumn();
dgc.Header = dc.ColumnName;
dgc.Width = 100;
dgc.IsReadOnly = true;
DataTemplate dtm = new DataTemplate();
FrameworkElementFactory outer = new FrameworkElementFactory(typeof(ComboBox));
dtm.VisualTree = outer;
dgc.CellTemplate = dtm;
dtgrdAtlas.Columns.Add(dgc);
i want to bind an array to this combo box.
how do i do that.
This code is in a seperate function where i add columns to data grid and my string array is in seperate function/class.
To bind a list to a ComboBox you need to set the ItemsSource, or Binding a List to the ItemsSource.
Here in this example I set directly the ItemsSource :
MyCombobox.ItemsSource = new List<int> {2, 3, 4 ,5, 6};
I am creating a listbox with itemsource of type dataview. I want to scroll the listbox to praticular item which is not selected. I am using the following code for selected item.
Code:
Binding listbox:
DataView dv = newDt.DefaultView;
dv.Sort = "Count Desc";
lbResult.DataContext = dv;
To get the row based on id:
var selectResult = from mypro in albumDetails.ToTable().AsEnumerable() where mypro.Field<string>("ID")==search.ID select mypro;
if (lbResult.SelectedItem != null)
{
lbResult.ScrollIntoView(**lbResult.Items[0]**);
}
How to get the index if the row in the list box.
Geetha
I don't know what is the albumDetails object. Here is the code to get index from DataView.
DataRow row = dataview.Select("ID='" + search.ID + "'")[0];
int i= dataview.Rows.IndexOf(row);
I have been confused while setting SelectedItem programmaticaly in wpf applications with Net Framework 3.5 sp1 installed. I have carefully read about hundred posts \topics but still confused((
My xaml:
<ComboBox name="cbTheme">
<ComboBoxItem>Sunrise theme</ComboBoxItem>
<ComboBoxItem>Sunset theme</ComboBoxItem>
</ComboBox>
If I add IsSelected="True" property in one of the items - it's dosn't sets this item selected. WHY ?
And i was try different in code and still can't set selected item:
cbTheme.SelectedItem=cbTheme.Items.GetItemAt(1); //dosn't work
cbTheme.Text = "Sunrise theme"; //dosn't work
cbTheme.Text = cbTheme.Items.GetItemAt(1).ToString();//dosn't work
cbTheme.SelectedValue = ...//dosn't work
cbTheme.SelectedValuePath = .. //dosn't work
//and even this dosn't work:
ComboBoxItem selcbi = (ComboBoxItem)cbTheme.Items.GetItemAt(1);//or selcbi = new ComboBoxItem
cbTheme.SelectedItem = selcbi;
The SelectedItem is not readonly property, so why it wan't work?
I think thats should be a Microsoft's problems, not my. Or I have missed something??? I have try playing with ListBox, and all work fine with same code, I can set selections, get selections and so on.... So what can I do with ComboBox ? Maybe some tricks ???
To select any item in the ComboBox and to set it as default item selected just use the below line:
combobox.SelectedIndex = 0; //index should be the index of item which you want to be selected
If i add the combobox and items programmatically, this works for me:
ComboBox newCombo = new ComboBox();
ComboBoxItem newitem = new ComboBoxItem();
newitem.Content = "test 1";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 2";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 3";
newCombo.Items.Add(newitem);
newCombo.SelectedItem = ((ComboBoxItem)newCombo.Items[1]);
newCombo.Text = ((ComboBoxItem)newCombo.Items[1]).Content.ToString();
newStack.Children.Add(newCombo);
It also works if it set the ItemSource property programmatically, then set the text to the selected value.
Create a public property in your viewmodel for the theme list and one for the selected item:
private IEnumerable<string> _themeList;
public IEnumerable<string> ThemeList
{
get { return _themeList; }
set
{
_themeList = value;
PropertyChangedEvent.Notify(this, "ThemeList");
}
}
private string _selectedItem;
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
PropertyChangedEvent.Notify(this,"SelectedItem");
}
}
bind your combobox in xaml to the properties like this:
<ComboBox
Name="cbTheme"
ItemsSource="{Binding ThemeList}"
SelectedItem="{Binding SelectedItem}">
</ComboBox>
now all you do is add items to the ThemeList to populate the combobox. To select an item in the list, set the selected property to the text of the item you want selected like this:
var tmpList = new List<string>();
tmpList.Add("Sunrise theme");
tmpList.Add("Sunset theme");
_viewModel.ThemeList = tmpList;
_viewModel.SelectedItem = "Sunset theme";
or try setting the selected item to the string value of the item you want selected in your own code if you want to use the code you currently have - not sure if it will work but you can try.
If you know the index of the item you want to set, in this case it looks like you are trying to set index 1, you simply do:
cbTheme.SelectedIndex = 1;
I found that when you don't know the index, that's when you have the real issue. I know this goes beyond the original question, but for Googlers on that count that want to know how to set the item when the index isn't known but the value you want to display IS known, if you are filling your dropdown with an ItemSource from a DataTable, for example, you can get that index by doing this:
int matchedIndex = 0;
if (dt != null & dt.Rows != null)
{
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
string myRowValue = dr["SOME_COLUMN"] != null ? dr["SOME_COLUMN"].ToString() : String.Empty;
if (myRowValue == "Value I Want To Set")
break;
else
matchedIndex++;
}
}
}
And then you do simply do cbTheme.SelectedIndex = matchedIndex;.
A similar iteration of ComboBoxItem items instead of DataRow rows could yield a similar result, if the ComboBox was filled how the OP shows, instead.
Is the ComboBox data bound?
If so you are probably better to do it through Binding rather than code ....
See this question ... WPF ListView Programmatically Select Item
Maybe create a new SelectableObject {Text = "Abc Theme", IsCurrentlySelected = True}
Bind a collection of SelectableObjects to the ComboBox.
Essentially setting the IsCurrentlySelected property in the model and having UI update from the Model.
Acording Answer 4
If you already add the Items in the Item source.
Fire the PropertyChangedEvent of the selectet Value.
tmpList.Add("Sunrise theme");
tmpList.Add("Sunset theme");
PropertyChangedEvent.Notify(this,"SelectedItem");