在我的列表 View 控件(或任何其他适合此情况的WPF控件)中,我希望有一个TextBlock可以对所有项目保持一致,而另一个TextBlock可以根据ObservableCollection中的值进行更改。这是我的代码当前的布局方式:
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>
模型
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));
}
}
}
后面的代码
this.DataContext = new MyVM();
StrVal属性在ListView中正确重复,但是ConstVal TextBlock不显示VM中包含的ConstVal。我猜这是因为ListView的ItemsSource是MyItems,并且我无法引用MyItems中包含的其他变量。
我的问题是:如何让ConstVal在将由MyItems的Observable集合控制的所有listviewitem的ViewModel中显示值。
最佳答案
我可以通过2种方式看到它。
1)您可以命名您所在的用户控件(x:Name = control或其他名称),然后执行。
<TextBlock x:Name="ConstVal" Text="{Binding ElementName=control, Path= DataContext.ConstVal, Mode=TwoWay}" />
2)使用相对源:
<TextBlock x:Name="ConstVal" Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.ConstVal, Mode=TwoWay}" />
编辑:
3)由于您嵌套项目的方式(即,没有引入新的数据上下文,您可以简单地执行以下操作:
<TextBlock x:Name="ConstVal" Text="{Binding Path=DataContext.ConstVal, Mode=TwoWay}" />
关于.net - 使用MVVM和WPF显示项目的一致值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038128/