Display Consistent Value of an Item using MVVM and WPF
        Posted  
        
            by Blake Blackwell
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Blake Blackwell
        
        
        
        Published on 2010-06-14T14:38:10Z
        Indexed on 
            2010/06/14
            14:42 UTC
        
        
        Read the original article
        Hit count: 249
        
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}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
Model
 public class MyItem
    {
        public string StrVal { get; set; }        
    }
ViewModel
  public class MyVM
    {        
        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";
        }
        public string ConstVal { get; set; }
        public ObservableCollection<MyItem> MyItems { get; set; }
    }
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.
© Stack Overflow or respective owner