我有一个MVVM应用程序。在WPF主窗口中,除其他控件外,我还有一个combox和一个textblock。
当我从组合框中选择一个值时,文本块文本应根据组合框中选择的项目动态更改其文本值(取决于组合框中所选项目的ID)。
我的问题是,当我在组合框中选择一个项目时,文本块文本不会更改,它始终具有默认值。任何想法如何解决这个问题?
我只想使用xaml做到这一点。
模型:
public class Item
{
#region Constructors
public Item() { }
public Item(int id, string desc)
{
this.Id = id;
this.Desc = desc;
}
#endregion
#region Properties
public int Id
{
get;
set;
}
public string Desc
{
get;
set;
}
#endregion
public override string ToString()
{
return this.Desc;
}
}
View 模型中的 MVVM属性:
private ObservableCollection<Item> _myItems;
public ObservableCollection<Item> MyItems
{
get { return _myItems; }
set { _myItems= value; }
}
查看:
<ComboBox x:Name="MyWPFCombo"
ItemsSource="{Binding MyItems}"/>
<TextBlock Padding="5 10 0 0">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="Select the items:" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=MyWPFCombo, Path=Id}" Value="10">
<Setter Property="Text" Value="Select the old items:" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
最佳答案
您需要提供两件事
1)您需要设置ComboBox的SelectedValuePath
。
<ComboBox x:Name="MyWPFCombo" SelectedValuePath="Id"
ItemsSource="{Binding MyItems}" />
2)在
DataTrigger
中,您需要提供路径作为SelectedValue
的ComboBox
,而不是PropertyName。<DataTrigger Binding="{Binding ElementName=MyWPFCombo, Path=SelectedValue}" Value="10">
<Setter Property="Text" Value="Select the old items:" />
</DataTrigger>
关于c# - WPF Textblock文本不会在组合框所选项目上动态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53857077/