I have the following DataGrid in WPF :
<DataGrid x:Name="dgPatientMedicationOrderList" Width="Auto" HorizontalAlignment="Stretch" RowHeight="40" Background="Transparent" HorizontalContentAlignment="Left"
GridLinesVisibility="None" RowHeaderWidth="0" VirtualizingStackPanel.VirtualizationMode="Standard" SelectedIndex="-1"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" AutoGenerateColumns="False" SelectionMode="Single"
IsSynchronizedWithCurrentItem="True" RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Stretch" IsReadOnly="True"
ItemsSource="{Binding PatientOrdersCollectionView}">
When a user clicks on a row in the DataGrid, it's SelectionChanged event is fired and the bound ViewModel command drives the View to load another user control corresponding to the DG row. In my view I am changing my datagrid's source binding from my ViewModel. Now the problem is that every time the ItemsSource is changed the SelectionChanged event is fired selecting the first item in the DataGrid; this is followed by the view loading the user control without the user explicitly selecting the DataGrid row. How can I prevent the DataGrid from selecting any Row when it's ItemsSource is changed ?
Simplified Demo Code:
XAML:
<Button Content="Change Source" Command="{Binding ChangeItemsSourceCmd}" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20" />
<StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Left" Orientation="Vertical">
<TextBlock Text="{Binding SelectedPerson.Id, StringFormat=ID: {0}}" />
<TextBlock Text="{Binding SelectedPerson.Name, StringFormat=Name: {0}}" />
<TextBlock Text="{Binding SelectedPerson.Gender, StringFormat=Gender: {0}}" />
<TextBlock Text="{Binding SelectedPerson.Country, StringFormat=Country: {0}}" />
</StackPanel>
</Grid>
ViewModel:
public class WindowViewModel : ViewModelBase
{
private Person _selectedPerson;
private ObservableCollection<Person> _personList;
public Person SelectedPerson
{
get { return _selectedPerson; }
set { RaisePropertyChange<Person>(() => SelectedPerson, ref _selectedPerson, ref value); }
}
public ObservableCollection<Person> PersonList
{
get { return _personList; }
set
{
SelectedPerson = null;
RaisePropertyChange<ObservableCollection<Person>>(() => PersonList, ref _personList, ref value);
}
}
public WindowViewModel()
{
PersonList = new ObservableCollection<Person>()
{
new Person() { Id=101, Name="Mahesh", Gender="Male", Country="India"},
new Person() { Id=102, Name="Srinivas", Gender="Male", Country="Sri Lanka"},
new Person() { Id=103, Name="Isha", Gender="Female", Country="United States"},
new Person() { Id=104, Name="Salim", Gender="Male", Country="Pakistan"}
};
}
public ICommand ChangeItemsSourceCmd
{
get
{
return new RelayCommand(ChangeItemsSourceCmdHandler);
}
}
private void ChangeItemsSourceCmdHandler()
{
PersonList = new ObservableCollection<Person>()
{
new Person() { Id=105, Name="Raman", Gender="Male", Country="Uganda"},
new Person() { Id=106, Name="Anurag", Gender="Male", Country="England"},
new Person() { Id=107, Name="Komal", Gender="Female", Country="Thailand"},
new Person() { Id=108, Name="Nitin", Gender="Male", Country="Africa"}
};
}
}
You should:
1.Add a SelectedItem Binding in your DataGrid:
SelectedItem="{Binding Selected, Mode=TwoWay}"
2.Have the related property (firing PropertyChanged of course)
public object Selected
{
get { return selected; }
set
{
selected = value;
OnPropertyChanged("Selected");
}
}
3.Set it to null in your Itemssource setter (or before you change it)
public IEnumerable PatientOrdersCollectionView
{
get { return patientOrdersCollectionView; }
set
{
Selected = null; // Put it to null here to unselect it from grid
patientOrdersCollectionView = value;
OnPropertyChanged("PatientOrdersCollectionView");
}
}
Should do the trick.
Related
Using the MVVM pattern in a WPF application, I want to set on the 'Editing State' of a records in row.
Every time the user starts editing a record by clicking on Edit button, that row should switch to the 'editing' mode.
Finished, he can save all changes in the row by clicking the same or another button
How can I set edit mode (IsReadOnly=true/false) for All cells in selected Row on click "Edit" button?
Any help is appreciated!
This is my current code:
XAML
<Window x:Class="TotalRows.TotalRowsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TotalRows"
mc:Ignorable="d"
x:Name="xMainWindow"
Title="RowsTotalWindow" Height="450" Width="800">
<Window.DataContext>
<local:ExampleData/>
</Window.DataContext>
<Grid>
<StackPanel >
<DataGrid x:Name="myGrid" IsReadOnly="True" CanUserAddRows="False" SelectionMode="Single" CanUserDeleteRows="False"
ItemsSource="{Binding ItemsViewCollection}" RowDetailsVisibilityMode="Collapsed"
SelectedItem="{Binding SelectedItemRow, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DockPanel HorizontalAlignment="Stretch">
<ToggleButton x:Name="btnEditItem" Content="Edit" Width="50" Height="20" Margin="0 0 3 0"
Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.UpdateItemCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=DataContext}"/>
</DockPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn x:Name="gr" Binding="{Binding Group}" Header="Gr" Width="30" />
<DataGridTextColumn x:Name="one" Binding="{Binding Col_1}" Header="h1" Width="30" />
<DataGridTextColumn x:Name="two" Binding="{Binding Col_2}" Header="h2" Width="30" />
<DataGridTextColumn x:Name="tree" Binding="{Binding Col_3}" Header="h3" Width="30" />
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
</Window>
Code Behind
namespace TotalRows
{
public class ItemClass
{
public int Group { get; set; }
public string Title { get; set; }
public int Col_1 { get; set; }
public int Col_2 { get; set; }
public int Col_3 { get; set; }
}
public class ExampleData
{
private bool _IsReadMode;
public bool IsReadMode
{
get { return _IsReadMode; }
set
{
_IsReadMode = value;
OnPropertyChanged(nameof(IsReadMode));
}
}
private ItemClass _selectedItem = null;
public ItemClass SelectedItemRow
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItemRow));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<ItemClass> _items;
public ObservableCollection<ItemClass> Items
{
get
{
return _items;
}
set
{
if (_items != value)
{
_items = value;
OnPropertyChanged(nameof(Items));
}
}
}
private ICollectionView _itemsViewCollection;
public ICollectionView ItemsViewCollection
{
get
{
return _itemsViewCollection;
}
set
{
if (_itemsViewCollection != value)
{
_itemsViewCollection = value;
OnPropertyChanged(nameof(ItemsViewCollection));
}
}
}
public ICommand UpdateItemCommand { get; private set; }
public ExampleData()
{
IsReadMode = true;
UpdateItemCommand = new ViewModelCommand(param => updateItemCommand(param));
Items = new ObservableCollection<ItemClass>()
{
new ItemClass() {Group=1, Title="Item1", Col_1=100, Col_2=150, Col_3=250},
new ItemClass() {Group=2, Title="Item1", Col_1=50, Col_2=2, Col_3=200},
new ItemClass() {Group=2, Title="Item2", Col_1=50, Col_2=100, Col_3=40},
new ItemClass() {Group=3, Title="Item1", Col_1=60, Col_2=25, Col_3=230},
new ItemClass() {Group=3, Title="Item2", Col_1=30, Col_2=25, Col_3=0},
new ItemClass() {Group=3, Title="Item3", Col_1=9, Col_2=100, Col_3=20},
new ItemClass() {Group=4, Title="Item1", Col_1=46, Col_2=32, Col_3=30},
};
ItemsViewCollection = CollectionViewSource.GetDefaultView(Items);
ItemsViewCollection.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
}
private void updateItemCommand(object param)
{
IsReadMode = !IsReadMode;
}
}
}
Do you realise f2 switches the current row into edit mode?
CommandManager.RegisterClassInputBinding(ownerType, new InputBinding(BeginEditCommand, new KeyGesture(Key.F2)));
CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(BeginEditCommand, new ExecutedRoutedEventHandler(OnExecutedBeginEdit), new CanExecuteRoutedEventHandler(OnCanExecuteBeginEdit)));
You could bind your edit button to a command in the ExampleData viewmodel and pass a reference to the specific ItemClass as a command parameter.
Use relativesource binding to get to that command.
ExampleData owns that collection so you can set properties on that instance and stash a reference or index to the last one they edited set the flag back. Or iterate through the whole collection.
Seems you know how to write a command but I recommend the community mvvm toolkit and relaycommand.
Your binding would be something like
<Button Command="{Binding DataContext.EditThisOneCommand
, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}">
The command parameter passes the row to an Icommand so will be a parameter passed to your command.
A similar command I happen to have.
private RelayCommand<Thing> _colourCommand;
public RelayCommand<Thing> ColourCommand
{
get
{
return _colourCommand
?? (_colourCommand = new RelayCommand<Thing>(
_thing =>
{
_thing.Row = Items.IndexOf(_thing);
},
_thing => CanUserClick));
}
}
You would of course have EditThisOneCommand
You then have to tell the UI to issue a BeginEditCommand.
And then you need to tell the UI to issue a CommitEditCommand when you finish.
CommandManager.RegisterClassCommandBinding(ownerType, new CommandBinding(CommitEditCommand, new ExecutedRoutedEventHandler(OnExecutedCommitEdit), new CanExecuteRoutedEventHandler(OnCanExecuteCommitEdit)));
These commands are source from the datagrid.
You could instead just bind those datagrid commands to buttons and not have this flag.
A datagridrow has a property IsEditing. You might be able to bind that onewaytosource to your flag. You'd set that binding via a style.
Not sure why you'd want to, but you could take a look at that.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.datagridrow.isediting?view=windowsdesktop-7.0
I have a ListBox control with TypeUsers.When I select some record in Listbox and update Name in TextBox the Name property/textbox return always null. Never take value from TextBox, always null ?
Image description here
This is my code
<ListBox x:Name="LstTypeUsers"
Grid.Row="0" Grid.Column="4"
Width="220" Height="120"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ItemsSource="{Binding TypeUsers}"
DisplayMemberPath="Name">
</ListBox>
<TextBox
Grid.Row="0" Grid.Column="2"
x:Name="txtName"
HorizontalAlignment="Left" Height="23"
TextWrapping="Wrap"
VerticalAlignment="Top" Width="170"
Text="{Binding ElementName=LstTypeUsers, Path=SelectedItem.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
Validation.ErrorTemplate="{x:Null}"/>
<Button
Grid.Column="0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="100" Height="30"
Command="{Binding UpdateTypeUserCmd}"
Grid.ColumnSpan="3" Margin="20,90,0,0">
<StackPanel Orientation="Horizontal">
<Image Source="/Images/Save.png" />
<TextBlock Width="55" Height="18" ><Run Text=" "/><Run Text="Update"/></TextBlock>
</StackPanel>
</Button>
EDIT
// Model class
public class UserType: INotifyPropertyChanged
{
[Key]
private int usertypeId;
public int UserTypeId
{
get
{
return this.usertypeId;
}
set
{
this.usertypeId = value;
OnPropertyChanged("UserTypeId");
}
}
[MaxLength(200)]
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
OnPropertyChanged("Name");
}
}
[Required]
private bool status;
public bool Status
{
get
{
return this.status;
}
set
{
this.status = value;
OnPropertyChanged("Status");
}
}
public virtual ObservableCollection<User> User { get; private set; }
public UserType()
{
this.User = new ObservableCollection<User>();
}
}
// ViewModelBase class
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// UserTypeViewModel
public class UserTypeViewModel
private UserType _userType;
private ObservableCollection<UserType> _UserTypeList;
// Constructor
public UserTypeViewModel()
{
_userType = new UserType();
_UserTypeList = new ObservableCollection<UserType>(GetUserTypeAll());
}
public ObservableCollection<TypeUsers> TypeUsers
{
get
{
return _UserTypeList;
}
set
{
_UserTypeList = value;
//OnPropertyChanged("TypeUsers");
}
}
public string Name
{
get
{
return _userType.Name;
}
set
{
_userType.Name = value;
//OnPropertyChanged("Name");
}
}
Thank you.
Implement INotifyPropertyChanged interface in UserType class.
You're binding directly to the WPF control (ListBox) and not the ViewModel. I suggest you add a property in your ViewModel that will bind to the TextBox.Text property, once the data changes or the user had changed the value in the TextBox, then the data will update and be reflected in the UI.
Also, if I remember correctly, at launch, the SelectedItem property of the ListBox is null, so there might be a problem there too, but I'm not certain about that...
I have resolved my problem. I have also implemented INotifyPropertyChanged interface in Model class. I'm new in WPF MVVM and I read that this interface is implemented only in the ViewModel for connection with View. Now I have implemented in both classes and everything works great.
Thanks Everyone.
I am a newbie to MVVM. I have two grid's inside by main window where one grid contains a listbox towards left side and other grid on the right side contains list view and 2 buttons.
I am able to add items to listview and even figure out how to get the selected item from list view. Once I select the item on list view and click a button(Connect), listbox towards left shud get updated with items which I have added from viewmodel class.
View below shows Listbox towards my left:
<Grid Grid.Column="0" Name="BoardTabSelect" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBox Name="ButtonPanel"
ItemsSource="{Binding BoardTabs, Mode=TwoWay}"
SelectedItem="{Binding SelectedTab, Mode=TwoWay}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name="BoardtabChanger"
Margin="53,27,0,0"
Text="{Binding TabOperation}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
View below shows listview towards Right along with 2 Buttons:
<Grid Grid.Row="0" Name="MainConnectGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<ListView Name="listView"
ItemsSource="{Binding Products}"
SelectedItem="{Binding SelectedProduct, Mode=TwoWay}">
<ListView.View>
<GridView>
<GridViewColumn Width="300"
Header="Name"
DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Width="283"
Header="Connection Status"
DisplayMemberBinding="{Binding Connection_Status}" />
</GridView>
</ListView.View>
</ListView>
<Button Content="Connect"
Height="23" Width="100"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="55,519,0,0"
Name="ConnectBtnGrid"
Command="{Binding Path=ConnectCommand}" />
<Button Content="Disconnect"
Height="23" Width="100"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="446,519,0,0"
Name="DisconnectBtn"
Command="{Binding Path=DisconnectCommand}" />
</Grid>
VIEW MODEL:
public class ProductViewModel : INotifyPropertyChanged
{
public List<Product> m_Products;
public List<Product> m_BoardTabs;
public ProductViewModel()
{
m_Products = new List<Product>()
{
new Product() {Name = "Bavaria", Connection_Status = "Disconnected"},
new Product() {Name = "Redhook", Connection_Status = "Disconnected"},
};
m_BoardTabs = new List<Product>()
{
new Product() {TabOperation = "Connect"}
};
}
public List<Product> Products { get; set; }
public List<Product> BoardTabs { get; set; }
private Product m_SelectedItem;
public Product SelectedProduct
{
get { return m_SelectedItem; }
set
{
m_SelectedItem = value;
NotifyPropertyChanged("SelectedProduct");
}
}
private Product m_SelectedTab;
public Product SelectedTab
{
get { return m_SelectedTab; }
set
{
m_SelectedTab = value;
NotifyPropertyChanged("SelectedTab");
}
}
private ICommand mUpdater;
public ICommand ConnectCommand
{
get
{
if (mUpdater == null)
mUpdater = new DelegateCommand(new Action(SaveExecuted), new Func<bool>(SaveCanExecute));
return mUpdater;
}
set { mUpdater = value; }
}
public bool SaveCanExecute()
{
return true;
}
public void SaveExecuted()
{
if (SelectedProduct.Connection_Status == "Disconnected" && SelectedProduct.Name == "Bavaria")
{
SelectedProduct.Connection_Status = "Connected";
m_BoardTabs.Add(new Product() { TabOperation = "I2C" });
m_BoardTabs.Add(new Product() { TabOperation = "Voltage" });
m_BoardTabs.Add(new Product() { TabOperation = "Codec" });
}
}
}
Inside the Save Executed method I am trying to add the items in listbox but when I run the application and select item from listview and press CONNECT Btn, the list does not get updated. My model class is complete with all three properties (Name, Connection Status and TabOperation)
BoardTabs and Products need to be an ObservableCollection<Product>. Otherwise WPF doesn't get informed about new items in the lists and thus can't update the UI.
Check properies of ProductViewModel. It implements INotifyPropertyChanged , and in Products, BoardTabs, you not notify the change .
public List<Product> Products
{
get
{
return m_Products;
}
set
{
m_Products = value;
NotifyPropertyChanged("Products")
}
}
public List<Product> BoardTabs
{
get
{
return m_BoardTabs;
}
set
{
m_BoardTabs = value;
NotifyPropertyChanged("BoardTabs")
}
}
I am using WPF having a strange issue with RadListBox SelectedItem databinding, trying to figure out but no luck. Following is my scenario
I am using Telerik Controls (RadListBox, and RadButton)
RadButton is placed inside a ItemsControl, RadListBox and ItemsControl are bind to same ItemsSource.
I am using PRISM and MVVM.
What I want is when I click on button, the same item is selected from RadListBox automatically, (This part working fine).
Problem: As soon as I click on any item of RadListBox and then click back on any button the item selection stops working.
Edit: I tried the same thing with standard WPF ListBox by adding attached behavior for selection changed event and attached property of Command and CommandParameter, it works fine, so it looks like an issue with Telerik RadListBox ?
Now let me come to code.
ViewModel Class
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public DelegateCommand<object> StudentSelected { get; set; }
public DelegateCommand<object> ButtonPressed { get; set; }
private void OnStudentSelected(object par)
{
//Debugger.Break();
if (handled == false)
{
Student std = par as Student;
if (std != null)
{
SelectedStudent = std;
}
}
handled = false;
}
private void OnButtonPressed(object par)
{
//Debugger.Break();
handled = true;
String std = par as String;
if (std != null)
{
foreach (Student st in _students)
{
if (st.Name.Equals(std))
{
SelectedStudent = st;
break;
}
}
}
}
private Student _selectedstudent;
private bool handled = false;
public MainViewModel()
{
StudentSelected = new DelegateCommand<object>(OnStudentSelected);
ButtonPressed = new DelegateCommand<object>(OnButtonPressed);
}
public Student SelectedStudent
{
get
{
return _selectedstudent;
}
set
{
_selectedstudent = value;
OnPropertyChanged("SelectedStudent");
}
}
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get
{
return _students;
}
set
{
_students = value;
OnPropertyChanged("Students");
}
}
}
public class Student
{
public String Name { get; set; }
public String School { get; set; }
}
MainView XAML
<telerik:RadListBox Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Students}" Command="{Binding StudentSelected}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=SelectedItem}" SelectedItem="{Binding SelectedStudent, Converter={StaticResource DebugConverter}}">
<!-- The above debug converter is just for testing binding, as long as I keep on clicking button the Converter is being called, but the moment I click on RadListBoxItem the Converter is not called anymore, even when I click back on buttons -->
<telerik:RadListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</telerik:RadListBox.ItemTemplate>
</telerik:RadListBox>
<Label Grid.Row="0" Grid.Column="1" Content="{Binding SelectedStudent.Name}"></Label>
<StackPanel Grid.Column="1" Grid.Row="1" Orientation="Horizontal">
<ItemsControl ItemsSource="{Binding Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<telerik:RadButton Width="100" Height="70" Content="{Binding Name}" Command="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}, Path=DataContext.ButtonPressed}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}">
</telerik:RadButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
and finally populating the ViewModel and setting the Datacontext
MainViewModel mvm = new MainViewModel();
ObservableCollection<Student> students = new ObservableCollection<Student>();
students.Add(new Student { Name = "Student 1", School = "Student 1 School" });
students.Add(new Student { Name = "Student 2", School = "Student 2 School" });
students.Add(new Student { Name = "Student 3", School = "Student 3 School" });
mvm.Students = students;
//Bind datacontext
this.DataContext = mvm;
Please give your suggestions and share you expertise from WPF Jargon?
Finally I figured out the issue, I just need to replace the RadListBox SelectedItem binding to TwoWay
<telerik:RadListBox Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Students}" Command="{Binding StudentSelected}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=SelectedItem}" SelectedItem="{Binding SelectedStudent, Mode,TwoWay, Converter={StaticResource DebugConverter}}">
I've just stuck in a problem to bind collection in ItemsControl with ItemTeplate that contains bounded ComboBox.
In my scenario I need to "generate" form that includes textbox and combobox for each item in collection and let user to update items. I could use DataGrid for that but I'd like to see all rows in edit mode, so I use ItemsControl with custom ItemTemplate.
It's ok to edit textboxes but when you try to change any ComboBox, all other ComboBoxes in other rows will change too.
Is it a bug or feature?
Thanks, Ondrej
Window.xaml
<Window x:Class="ComboInItemsControlSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="480" Width="640">
<Window.Resources>
<CollectionViewSource x:Key="cvsComboSource"
Source="{Binding Path=AvailableItemTypes}" />
<DataTemplate x:Key="ItemTemplate">
<Border BorderBrush="Black" BorderThickness="0.5" Margin="2">
<Grid Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="20" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding Path=ItemValue}" />
<ComboBox Grid.Column="2"
SelectedValue="{Binding Path=ItemType}"
ItemsSource="{Binding Source={StaticResource cvsComboSource}}"
DisplayMemberPath="Name"
SelectedValuePath="Value" />
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Path=SampleItems}"
ItemTemplate="{StaticResource ItemTemplate}"
Margin="10" />
</Grid>
Window.xaml.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel
{
public ViewModel()
{
SampleItems = new List<SampleItem> {
new SampleItem { ItemValue = "Value 1" },
new SampleItem { ItemValue = "Value 2" },
new SampleItem { ItemValue = "Value 3" }
};
AvailableItemTypes = new List<SampleItemType> {
new SampleItemType { Name = "Type 1", Value = 1 },
new SampleItemType { Name = "Type 2", Value = 2 },
new SampleItemType { Name = "Type 3", Value = 3 },
new SampleItemType { Name = "Type 4", Value = 4 }
};
}
public IList<SampleItem> SampleItems { get; private set; }
public IList<SampleItemType> AvailableItemTypes { get; private set; }
}
public class SampleItem : ObservableObject
{
private string _itemValue;
private int _itemType;
public string ItemValue
{
get { return _itemValue; }
set { _itemValue = value; RaisePropertyChanged("ItemValue"); }
}
public int ItemType
{
get { return _itemType; }
set { _itemType = value; RaisePropertyChanged("ItemType"); }
}
}
public class SampleItemType : ObservableObject
{
private string _name;
private int _value;
public string Name
{
get { return _name; }
set { _name = value; RaisePropertyChanged("Name"); }
}
public int Value
{
get { return _value; }
set { _value = value; RaisePropertyChanged("Value"); }
}
}
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Picture
here you can see the result on picture
I believe it's because you're binding to a CollectionViewSource, which tracks the current item. Try binding directly to your list instead, which won't track the current item
<ComboBox Grid.Column="2"
SelectedValue="{Binding Path=ItemType}"
DisplayMemberPath="Name"
SelectedValuePath="Value"
ItemsSource="{Binding RelativeSource={
RelativeSource AncestorType={x:Type ItemsControl}},
Path=DataContext.AvailableItemTypes}" />
While you have a combobox in each row, it doesnt see these comboboxes as being seperate. i.e. They are all using the same collection, and the same selectedValue, so when a value changes in one box, it changes in all of them.
The best way to fix this is to add the SampleItemType collection as a property on your SampleItem model and to then bind the combo box to that property.