WPF Textblock text does not change dynamically on

2019-08-28 08:16发布

问题:

I have a MVVM app. In main WPF window I have a combox and a textblock among other controls.

When I select a value from the combobox, the textblock text should change its text value dynamically according to the item selected in the combobox (depending on the id of the selected item in combobox).

My problem is that when I select a item in the combobox, textblock text does not change, it always have the default value. Any ideas how to solve this?

I want to do this using xaml only.

Model:

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;
    }
}

MVVM Property in view model:

private ObservableCollection<Item> _myItems;
public ObservableCollection<Item> MyItems
{
    get { return _myItems; }
    set { _myItems= value; }
}

View:

<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:

You need to provide two things

1) You need to set the SelectedValuePath of ComboBox.

 <ComboBox x:Name="MyWPFCombo"       SelectedValuePath="Id"  
      ItemsSource="{Binding MyItems}" />

2) In DataTrigger you need to provide the Path as SelectedValue of ComboBox not the PropertyName.

<DataTrigger Binding="{Binding ElementName=MyWPFCombo, Path=SelectedValue}" Value="10">
                        <Setter Property="Text" Value="Select the old items:" />
                    </DataTrigger>


回答2:

You are binding to the Id property of your ComboBox, however, this property doesn't exist there. You need to use the SelectedItem property to access the selected item and thus its properties :

<DataTrigger Binding="{Binding SelectedItem.Id, ElementName=MyWPFCombo}" Value="10">
    <Setter Property="Text" Value="Select the old items:" />
</DataTrigger>