I need to present a WPF GridView where one column is a Combobox, The user can select one value from the list or enter a new value so I set the IsComboBoxEditable to true but the problem is that if the user types a value that is not in the ItemsSource the Text is blank when the Combobox looses the focus.
Note : I don't want, when a new value is typed , this value to be
added to the ItemsSource. I only need to save it's string value in row
that bounded to it.
I also need DropDownOpened event, to populate it's ItemsSource.
Here is my code:
<telerik:GridViewDataColumn Header="Description">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<telerik:RadComboBox IsEditable="True" ItemsSource="{Binding Descriptions}" Text="{Binding Description1,Mode=TwoWay}" DropDownOpened="descriptionRadComboBox_DropDownOpened"/>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
Description1 is string property, and Descriptions is List of string that populate in runtime.(When DropDownOpened Event occurred)
Like you mentioned, your goal is, simply, to "Editable ComboBox".
(And, of course, you don't want to add new Item to ItemsSource)
<telerik:GridViewDataColumn UniqueName="description1" Header="Description">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Description1}"></TextBlock>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
<telerik:GridViewDataColumn.CellEditTemplate>
<DataTemplate>
<telerik:RadComboBox Name="SLStandardDescriptionsRadComboBox" IsEditable="True"
ItemsSource="{Binding DataContext.SLStandardDescriptions, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
DisplayMemberPath="SLStandardDescriptionTitle" DropDownOpened="Description_DropDownOpened">
</telerik:RadComboBox>
</DataTemplate>
</telerik:GridViewDataColumn.CellEditTemplate>
</telerik:GridViewDataColumn>
Codebehinde :
private void RadGridView_CellEditEnded(object sender, GridViewCellEditEndedEventArgs e)
{
if (e.Cell.Column.UniqueName == "description1")
{
RadComboBox combo = e.Cell.ChildrenOfType<RadComboBox>().FirstOrDefault();
if (combo != null)
{
List<Description> comboItems = combo.ItemsSource as List<Description>;
string textEntered = e.Cell.ChildrenOfType<RadComboBox>().First().Text;
bool result = comboItems.Contains(comboItems.Where(x => x.DescriptionTitle == textEntered).FirstOrDefault());
if (!result)
{
comboItems.Add(new Description { DescriptionTitle = textEntered });
combo.SelectedItem = new Description { DescriptionTitle = textEntered };
}
if (_viewModel.AccDocumentItem != null)
{
if (e.Cell.Column.UniqueName == "description1")
_viewModel.AccDocumentItem.Description1 = textEntered;
}
}
}
}
Here is the solution for .net DataGrid control:
<DataGrid ItemsSource="{Binding Path=Items}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Title}" ></DataGridTextColumn>
<DataGridComboBoxColumn SelectedValueBinding="{Binding ComboItem.ID}" DisplayMemberPath="ComboTitle" SelectedValuePath="ID">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.ComboItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.ComboItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
<Setter Property="IsEditable" Value="True" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
Surely you can do this using Telerik DataGrid control as well.
And here is my ViewModel:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
ComboItems = new ObservableCollection<ComboItem>()
{
new ComboItem(){ID=1,ComboTitle="ComboItem1"},
new ComboItem(){ID=2,ComboTitle="ComboItem2"},
new ComboItem(){ID=3,ComboTitle="ComboItem3"}
};
Items = new ObservableCollection<Item>()
{
new Item(){ID=1,Title="Item1",ComboItem=ComboItems[0]},
new Item(){ID=2,Title="Item2",ComboItem=ComboItems[1]},
new Item(){ID=3,Title="Item3",ComboItem=ComboItems[2]}
};
}
public ObservableCollection<Item> Items { get; set; }
public ObservableCollection<ComboItem> ComboItems { get; set; }
}
public class Item
{
public int ID { get; set; }
public string Title { get; set; }
public ComboItem ComboItem { get; set; }
}
public class ComboItem
{
public int ID { get; set; }
public string ComboTitle { get; set; }
}
Related
I have a table Called IGdaily with Field Trans_Category. I want to bind a DataGridComboBoxColumn displaying enum and binds its int value to datagrid cell Trans_Category.
My Enum
public enum Enm_Purch_Ret : short
{
Purchase = 1,
Sale = 2,
Return = 3
}
Viewmodel Vm_Purchase
public class Vm_Purchase : INotifyPropertyChanged
{
private IGoldEntities db = new IGoldEntities();
public ObservableCollection<IGdaily> Vm_IGdaily { get; set; }
public ObservableCollection<Enm_Purch_Ret> Vm_Enum_P_R { get; set; }
public Vm_Purchase()
{
Vm_IGdaily = new ObservableCollection<IGdaily>();
Vm_Enum_P_R = new ObservableCollection<Enm_Purch_Ret>(Enum.GetValues(typeof(Enm_Purch_Ret)).Cast<Enm_Purch_Ret>().ToList());
}
public ObservableCollection<IGdaily> IGDailys
{
get { return Vm_IGdaily; }
set { Vm_IGdaily = value; NotifyPropertyChanged(); }
}
public ObservableCollection<Enm_Purch_Ret> Enm_Purch_Rets
{
get { return Vm_Enum_P_R; }
set { Vm_Enum_P_R = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
In XAML
<Window.DataContext>
<local:Vm_Purchase/>
</Window.DataContext>
<DataGrid x:Name="DG" ItemsSource="{Binding IGDailys}" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="Cell" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding GroupName}" Header="Name" Width="200"/>
<DataGridComboBoxColumn Header="Item/Metal" SelectedValueBinding="{Binding Trans_Category}" SelectedValuePath="{Binding Path=Enm_Purch_Rets, StringFormat='\{0:D\}'}" DisplayMemberPath="Enm_Purch_Ret">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Enm_Purch_Rets, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Enm_Purch_Rets , RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
<DataGridTextColumn Binding="{Binding Trans_Category}" ClipboardContentBinding="{x:Null}" FontSize="14" Header="Metal Id" Width="100"/>
</DataGrid.Columns>
</DataGrid>
public partial class IGdaily
{
public int GDaily_Id { get; set; }
public int DailyMast_Id { get; set; }
public int ItemGroup_Id { get; set; }
public int Item_Id { get; set; }
public int Trans_Category { get; set; }
}
Please help what is my mistake in binding. I am new to MVVM pattern.
please explain
Thanks
You can't set an int property to a Enm_Purch_Ret value because there is no implicit conversion between these two types.
But you could use a converter class that peforms the conversion for you:
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Enm_Purch_Ret e = (Enm_Purch_Ret)value;
return (int)e;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
int i = (int)value;
return (Enm_Purch_Ret)i;
}
}
Usage:
<DataGrid x:Name="DG" ItemsSource="{Binding IGDailys}" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="Cell" >
<DataGrid.Resources>
<local:EnumConverter x:Key="conv" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding GroupName}" Header="Name" Width="200"/>
<DataGridComboBoxColumn Header="Item/Metal"
SelectedItemBinding="{Binding Trans_Category, Converter={StaticResource conv}}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Enm_Purch_Rets, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Enm_Purch_Rets , RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
<DataGridTextColumn Binding="{Binding Trans_Category}" ClipboardContentBinding="{x:Null}" FontSize="14" Header="Metal Id" Width="100"/>
</DataGrid.Columns>
</DataGrid>
I have a nested datagrid where I have + and - buttons that are bound to RelayCommands that add a new row or delete the current one respectively. The minus button command's CanExecute logic is supposed to disable the current row's minus button if only one item is left in its category.
The problem is that it disables all minus buttons in all categories because of its template nature.
Image
How can this be mitigated?
Here's the code.
XAML
<Grid>
<DataGrid x:Name="dataGrid1"
ItemsSource="{Binding DataCollection}"
SelectedItem="{Binding dataCollectionSelectedItem, Mode=TwoWay}"
AutoGenerateColumns="False"
CanUserAddRows="false" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Item/Price" Width="*">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<DataGrid x:Name="dataGridItem"
ItemsSource="{Binding Items}"
SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.itemsSelectedItem, Mode=TwoWay}"
Background="Transparent"
HeadersVisibility="None"
AutoGenerateColumns="False"
CanUserAddRows="false" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Binding="{Binding Price}" Width="50"/>
<DataGridTemplateColumn Header="Button">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AddItem }" Width="20" Height="20">+</Button>
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.DeleteItem }" Width="20" Height="20">-</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Category" Binding="{Binding Category}" Width="Auto"/>
<DataGridTemplateColumn Header="Buttons">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AddCategory}" Width="20" Height="20">+</Button>
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.DeleteCategory}" Width="20" Height="20">-</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
C#
public class Item
{
public string Name { get; set; }
public int Price { get; set; }
}
public class DataTable
{
public ObservableCollection<Item> Items { get; set; }
public string Category { get; set; }
}
public class RelayCommand : ICommand
{
private Action<object> executeDelegate;
readonly Predicate<object> canExecuteDelegate;
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new NullReferenceException("execute");
executeDelegate = execute;
canExecuteDelegate = canExecute;
}
public RelayCommand(Action<object> execute) : this(execute, null) { }
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return canExecuteDelegate == null ? true : canExecuteDelegate(parameter);
}
public void Execute(object parameter)
{
executeDelegate.Invoke(parameter);
}
}
public class ViewModel
{
public ObservableCollection<DataTable> DataCollection { get; set; }
public DataTable dataCollectionSelectedItem { get; set; }
public Item itemsSelectedItem { get; set; }
public RelayCommand DeleteCategory { get; private set; }
public RelayCommand AddCategory { get; private set; }
public RelayCommand DeleteItem { get; private set; }
public RelayCommand AddItem { get; private set; }
public ViewModel()
{
DataCollection = new ObservableCollection<DataTable>
{
new DataTable() {
Items = new ObservableCollection<Item> {
new Item { Name = "Phone", Price = 220 },
new Item { Name = "Tablet", Price = 350 },
},
Category = "Electronic gadgets" },
new DataTable() {
Items = new ObservableCollection<Item> {
new Item { Name = "Teddy Bear Deluxe", Price = 2200 },
new Item { Name = "Pokemon", Price = 100 },
},
Category = "Toys" }
};
DeleteItem = new RelayCommand(innerDeleteItem, canUseDeleteItem);
AddItem = new RelayCommand(innerAddItem, canUseAddItem);
}
public void innerDeleteItem(object parameter)
{
var collectionIndex = DataCollection.IndexOf(dataCollectionSelectedItem);
if (DataCollection[collectionIndex].Items.Count != 1)
{
DataCollection[collectionIndex].Items.Remove(itemsSelectedItem);
CollectionViewSource.GetDefaultView(DataCollection).Refresh();
}
}
public bool canUseDeleteItem(object parameter)
{
var collectionIndex = DataCollection.IndexOf(dataCollectionSelectedItem);
if ((dataCollectionSelectedItem != null) && (DataCollection[collectionIndex].Items.Count == 1))
{
return false;
}
else return true;
}
public void innerAddItem(object parameter)
{
var collectionIndex = DataCollection.IndexOf(dataCollectionSelectedItem);
var itemIndex = DataCollection[collectionIndex].Items.IndexOf(itemsSelectedItem);
Item newItem = new Item() { Name = "Item_Name", Price = 0 };
DataCollection[collectionIndex].Items.Insert(itemIndex + 1, newItem);
CollectionViewSource.GetDefaultView(DataCollection).Refresh();
}
public bool canUseAddItem(object parameter)
{
return true;
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ViewModel newViewModel = new ViewModel();
this.DataContext = newViewModel;
}
}
You're binding your two Commands to Window's Data Context, and it should bind to DataGrid's Data Context.
Change your xaml to:
<StackPanel Orientation="Horizontal">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.AddItem }" Width="20" Height="20">+</Button>
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteItem }" Width="20" Height="20">-</Button>
</StackPanel>
I have eventually set the button's CanExecute to always return true and styled the button with a custom trigger that disables it when Items.Count turns 1. Perhaps there are more elegant solutions but at least this one works for me.
<Button Content="-"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.DeleteItem }"
Width="20" Height="20">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=Items.Count }" Value="1">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
In my TreeView I use two differnt classes for binding. For example, I have a Group what can have ChildGroup and can have Items.
Example code of this classes:
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
public class Group
{
public Group(string name)
{
Name = name;
items = new ObservableCollection<Item>();
groups = new ObservableCollection<Group>();
}
public string Name { get;
set;
}
private ObservableCollection<Item> items;
private ObservableCollection<Group> groups;
public ObservableCollection<Item> Items
{
get { return items; }
}
public ObservableCollection<Group> Groups
{
get { return groups; }
}
public IEnumerable<object> AllItems
{
get
{
foreach (var group in groups)
{
yield return group;
}
foreach (var item in items)
{
yield return item;
}
}
}
}
public class Item
{
public Item(string name)
{
ItemName = name;
}
public string ItemName
{
get;
set;
}
}
}
To bind it to TreeView I use following template
<Grid>
<TreeView Name="treeView">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type WpfApplication1:Group}"
ItemsSource="{Binding AllItems}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type WpfApplication1:Item}">
<TextBlock Text="{Binding ItemName}" FontStyle="Italic"/>
</DataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
It is easy.
The problem is that I need to change ItemTemplate when Is selected. And I need to change only then Item class selected.
I can do it if only one class use for binding. It also easy using Style and Trigger, like this:
<TreeView Name="treeView1" Grid.Column="1">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type WpfApplication1:Group}"
ItemsSource="{Binding AllItems}"
x:Key="groupTemplate">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type WpfApplication1:Group}"
ItemsSource="{Binding AllItems}"
x:Key="selectedGroupTemplate">
<TextBlock Text="{Binding Name}" FontStyle="Italic" FontWeight="Bold" FontSize="14"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate" Value="{StaticResource groupTemplate}"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="HeaderTemplate" Value="{StaticResource selectedGroupTemplate}"/>
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
But I have a trouble for multiclass binding.
How can I change SelectedItem template then multiclass binding using? Any ideas?
My code behind sample:
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window2.xaml
/// </summary>
public partial class Window2 : Window
{
private ObservableCollection<Group> _groups;
public ObservableCollection<Group> Groups
{
get { return _groups; }
}
public Window2()
{
InitializeComponent();
InitGroups();
treeView.ItemsSource = _groups;
treeView1.ItemsSource = _groups;
}
private void InitGroups()
{
_groups = new ObservableCollection<Group>();
Group group1 = new Group("Group1");
group1.Groups.Add(new Group("Group1.1"));
group1.Groups.Add(new Group("Group1.2"));
group1.Groups.Add(new Group("Group1.3"));
group1.Items.Add(new Item("Item1.1"));
group1.Items.Add(new Item("Item1.2"));
group1.Groups[1].Items.Add(new Item("Item1.2.1"));
group1.Groups[1].Items.Add(new Item("Item1.2.2"));
_groups.Add(group1);
Group group2 = new Group("Group2");
group2.Groups.Add(new Group("Group2.1"));
group2.Groups.Add(new Group("Group2.2"));
group2.Items.Add(new Item("Item2.1"));
group2.Groups[0].Items.Add(new Item("Item2.1.1"));
group2.Groups[0].Items.Add(new Item("Item2.1.1"));
_groups.Add(group2);
}
}
}
Result
Now I think to use TreeView.HeaderTemplateSelector, but may be exists way to use only xaml.
Thanks.
There are a number of ways to acheive your desired result. If you are sure that your DataTemplate will only be used in TreeViewItem objects, then the easiest is simply to bind directly to the TreeViewItem.IsSelected property and then react to the change in your DataTemplate:
<DataTemplate DataType="{x:Type WpfApplication1:Item}">
<TextBlock Text="{Binding ItemName}">
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource=
{RelativeSource FindAncestor, AncestorType={x:Type TreeViewItem}}, FallbackValue=False}"
Value="True">
<Setter Property="TextBlock.FontStyle" Value="Italic" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
I'm relatively new to WPF and am having a hard time binding a custom class to a datagrid. While the text properties are OK (they are read-only anyway), the togglebuttons for the boolean properties are not updated in my item list, and they are also not displayed according to the values set initially. They do however respond correctly to clicks in the UI.
<Style x:Key="ToggleImageStyleBien" TargetType="ToggleButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<Image Name="img" Source="Images/transp.png"/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="ToggleButton.IsChecked" Value="True">
<Setter TargetName="img" Property="Source" Value="Images/good.png"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Here's the DataGrid itself:
<DataGrid AutoGenerateColumns="False" Height="Auto" Name="dataGridRevision" Width="Auto" Margin="6,6,6,0" ItemsSource="{Binding}" VerticalScrollBarVisibility="Auto" VerticalGridLinesBrush="{x:Null}">
<DataGrid.Columns>
<DataGridTextColumn Header="Code" Binding="{Binding Code}" Visibility="Collapsed"/>
<DataGridTextColumn Header="DescripciĆ³n" Binding="{Binding Description}" IsReadOnly="True"/>
<DataGridTemplateColumn Header="Bien">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ToggleButton Style="{StaticResource ToggleImageStyleBien}" Click="ToggleButton_Click" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=ReviewItem.Good, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Comentario" />
</DataGrid.Columns>
</DataGrid>
This is the class I'm binding to:
public class ReviewItem
{
public string Code { set; get; }
public string Description { set; get; }
public bool Good { set; get; }
public bool Bad { set; get; }
public string Comment { set; get; }
}
As far as I can tell, I'm not using the right Binding property in the ToggleButton, but I have tried a lot and have run out of ideas. The list properties are not changing on click, the values are not displayed according to the data.
Please help...
Thanks!
Joerg.
Changed the class to this, based on other examples found:
public class ReviewItem : INotifyPropertyChanged
{
public string Code { set; get; }
public string Description { set; get; }
public bool Bad { set; get; }
public string Comment { set; get; }
private bool _isChecked;
public bool Good
{
get { return _isChecked; }
set
{
System.Diagnostics.Debug.WriteLine("Good = " + value);
_isChecked = value;
OnPropertyChanged("Good");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
You are currently binding to UserControl.ReviewItem, which is not a valid property on a UserControl.
Try binding to DataContext.ReviewItem instead which will bind to UserControl.DataContext.ReviewItem
If you do not mean to bind to UserControl.DataContext.ReviewItem.Good, and instead want to bind to DataGrid.ReviewItems[x].Good, then you only need to bind IsChecked="{Binding Good}". This is because the default DataContext on a DataGridCell is the row's data item, so if your collection contains a list of ReviewItems, the DataContext of the cell is already set to a ReviewItem
Also, I would highly recommend using Snoop for debugging WPF bindings. You can use it on your application to see what the DataContext is for individual UI Elements, and figure out if your bindings are correct or not.
I've looked at the answers to various questions, but haven't managed to map the content in the answers to the problem I'm attempting to solve. I've reduced it down to the following code (representative of the outcome I'm trying to achieve), and basically want to be able to render the Person.TitleId as its corresponding Title.TitleText when the row isn't being edited, and have the drop-down bound correctly so that it displays the TitleTexts in the drop-down and writes the associated TitleId back to the Person record when its changed.
In short, what do I put in my <DataGridComboBoxColumn> to achieve this?
App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var viewModel = new ViewModels.MainWindowViewModel();
var mainWindow = new MainWindow();
mainWindow.DataContext = viewModel;
mainWindow.ShowDialog();
}
MainWindow.xaml
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Contacts}">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Title" SelectedItemBinding="{Binding Person}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Titles}"/>
<Setter Property="IsReadOnly" Value="True"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Titles}"/>
<Setter Property="DisplayMemberPath" Value="TitleText" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
Person.cs
public class Person
{
public int TitleId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}
Title.cs
public struct Title
{
public Title(int titleId, string titleText)
: this()
{
TitleId = titleId;
TitleText = titleText;
}
public string TitleText { get; private set; }
public int TitleId { get; private set; }
public static List<Title> GetAvailableTitles()
{
var titles = new List<Title>();
titles.Add(new Title(1, "Mr"));
titles.Add(new Title(2, "Miss"));
titles.Add(new Title(3, "Mrs"));
return titles;
}
}
MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
private ObservableCollection<Person> contacts;
private List<Title> titles;
public MainWindowViewModel()
{
titles = Title.GetAvailableTitles();
Contacts = new ObservableCollection<Person>();
Contacts.Add(new Person() { FirstName = "Jane", LastName = "Smith", TitleId = 2 });
}
public List<Title> Titles
{
get { return titles; }
}
public ObservableCollection<Person> Contacts
{
get { return contacts; }
set
{
if (contacts != value)
{
contacts = value;
this.OnPropertyChanged("Contacts");
}
}
}
}
ViewModelBase.cs
public class ViewModelBase : INotifyPropertyChanged
{
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Here is a working code. The key point here was to use SelectedValueBinding instead of SelecteItemBinding.
<DataGridComboBoxColumn Header="Title"
SelectedValueBinding="{Binding TitleId}"
SelectedValuePath="TitleId"
DisplayMemberPath="TitleText"
>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Titles}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Titles}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
#SnowBear's answer worked well for me. But I want to clarify a detail of the binding.
In #Rob's example, both Title and Person classes use TitleID.
Therefore, in #SnowBear's answer, in the binding:
SelectedValueBinding="{Binding TitleId}"
it wasn't immediately obvious to me which class and property was being bound.
Because the SelectedValueBinding attribute appeared on the DataGridComboBoxColumn, it is binding to the ItemsSource of the containing DataGrid. In this case the Contacts collection of Person objects.
In my case, the DataGrid's DataSource collection was attributed with a property that was named different from the ValuePath of the ComboBox's ItemSource collection. So my SelectedValueBinding's value was bound to a different property than the property named in the ComboBox's SelectedValuePath.