In my list view control (or any other WPF control that will fit the situation), I would like to have one TextBlock that stays consistent for all items while another TextBlock that changes based on the value in the ObservableCollection. Here is how my code is currently laid out:
XAML
<ListView ItemsSource="{Binding Path=MyItems, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="StrVal" Text="{Binding StrVal}" />
<TextBlock x:Name="ConstVal" Text="{Binding MyVM.ConstVal, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Model
public class MyItem
{
public string StrVal { get; set; }
}
ViewModel
public MyVM()
{
ObservableCollection<MyItem> myItems = new ObservableCollection<MyItem>();
for (int i = 0 ; i < 10; i++)
myItems.Add(new MyItem { StrVal = i.ToString()});
MyItems = myItems;
ConstVal = "1";
}
private string _constVal;
public string ConstVal
{
get
{
return _constVal;
}
set
{
_constVal = value;
OnPropertyChanged("ConstVal");
}
}
public ObservableCollection<MyItem> MyItems { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string item)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(item));
}
}
}
Code Behind
this.DataContext = new MyVM();
The StrVal property repeats correctly in the ListView, but the ConstVal TextBlock does not show the ConstVal that is contained in the VM. I would guess that this is because the ItemsSource of the ListView is MyItems and I can't reference other variables outside of what is contained in the MyItems.
My question is: How do I get ConstVal to show the value in the ViewModel for all listviewitems that will be controlled by the Observable Collection of MyItems.