Reputation: 1
I have been working on dummy project to understand binding in DataGridComboBoxColumn and in that I have encountered to SelectedValuePath and SelectedValue Binding.
I have looked up to various source of other questions too to understand such as:
The problem in my code is it gets bound with SelectedItemBinding, but not with SelectedValuePath & SelectedValueBinding.
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication10
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public string Code { get; set; }
// Property for the composite value
public string CombinedValue => $"{ID}_{Name}_{Code}";
}
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Item _selectedItem;
public Item SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
}
public ObservableCollection<Item> Items { get; set; }
public ObservableCollection<string> Codes { get; set; }
public MainViewModel()
{
Items = new ObservableCollection<Item>
{
new Item { ID = 1, Name = "Item 1", Code = "A" },
new Item { ID = 2, Name = "Item 2", Code = "Z" },
new Item { ID = 3, Name = "Item 3", Code = "C" },
new Item { ID = 4, Name = "Item 4", Code = "A C" }
};
Codes = new ObservableCollection<string>(Items.Select(item => item.Code).Distinct());
SelectedItem = Items.FirstOrDefault();
}
}
}
I have tried below with SelectedItemBinding and it works
<DataGridComboBoxColumn Header="Code" SelectedItemBinding="{Binding Code}" Width="100" IsReadOnly="True">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding DataContext.Codes,
RelativeSource={RelativeSource AncestorType=Window}}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>
I want to implement above with SelectedValueBinding & SelectedValuePath.
I have tried this till now
<DataGridComboBoxColumn Header="Value-Binded" ItemsSource="{Binding DataContext.Items}"
SelectedValuePath="Code"
SelectedValueBinding="{Binding ID , UpdateSourceTrigger=PropertyChanged}"
>
</DataGridComboBoxColumn>
DataGrid defined as
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False" CanUserAddRows="False">
And DataContext as
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
Upvotes: 0
Views: 45