C# 如何使用XAML将数据绑定到祖先元素中的属性?
我正在使用C#和MVVM设计模式编写一个WPF应用程序 我有以下C# 如何使用XAML将数据绑定到祖先元素中的属性?,c#,wpf,xaml,mvvm,data-binding,C#,Wpf,Xaml,Mvvm,Data Binding,我正在使用C#和MVVM设计模式编写一个WPF应用程序 我有以下c#对象 public class ProductStyleGenericModel : BindableBase { public int Id { get; set; } public string Name { get; set; } public int? SelectedValue { get; set; } public IEnumerable<SelectListItem<
c#
对象
public class ProductStyleGenericModel : BindableBase
{
public int Id { get; set; }
public string Name { get; set; }
public int? SelectedValue { get; set; }
public IEnumerable<SelectListItem<int>> Items { get; set; }
}
最后,我有下面的XAML视图,它只显示一个列表框
。每个ListBoxItem
都有一个网格,其中TextBlock
位于左侧,而ComboBox
位于右侧
<GroupBox Header="Product Description">
<StackPanel>
<ListBox ItemsSource="{Binding Styles}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" />
<ComboBox ItemsSource="{Binding Items}"
Grid.Column="1"
SelectedValue="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, Path=SelectedValue, Mode=TwoWay}"
SelectedValuePath="Value"
DisplayMemberPath="Text"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</GroupBox>
我想装订可能是错的。请尝试以下方法:
<ComboBox ItemsSource="{Binding Items}"
Grid.Column="1"
SelectedValue="{Binding SelectedValue}"
SelectedValuePath="Value"
DisplayMemberPath="Text"/>
我认为您要绑定到的SelectedValue属性位于当前数据上下文中。您绑定到的属性是ListBox控件上的SelectedValue,至少对我来说没有任何意义。除非BindableBase以某种方式打破了语言规则,否则您的任何属性都没有设置更改通知。您必须在每个集合访问器中实际引发ChangeNotification事件。自动实现属性不起作用。@Christopher
BindableBase
implementsINotifyPropertyChanged
,通过上面链接的Fody.PropertyChanged包,属性自动引发属性更改。包simple在编译时将raise属性更改注入到属性设置器中。
public class SelectListItem<T> : BindableBase
{
public T Value { get; set; }
public string Text { get; set; }
public SelectListItem(T value, string text)
{
Value = value;
Text = text;
}
}
<ComboBox ItemsSource="{Binding Items}"
Grid.Column="1"
SelectedValue="{Binding SelectedValue}"
SelectedValuePath="Value"
DisplayMemberPath="Text"/>