WPF Textblock文本不会在组合框所选项目上动态更改 [英] WPF Textblock text does not change dynamically on combobox selected item

查看:251
本文介绍了WPF Textblock文本不会在组合框所选项目上动态更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVVM应用程序。在WPF主窗口中,除了其他控件外,还有一个combox和一个textblock。

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

当我从组合框中选择一个值时,textblock文本应根据以下内容动态更改其文本值:

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).

我的问题是,当我在组合框中选择一个项目时,textblock文本会不会更改,它始终具有默认值。任何想法如何解决这个问题?

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?

我只想使用xaml来做到这一点。

I want to do this using xaml only.

模型

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属性

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

1) You need to set the SelectedValuePath of ComboBox.

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

2)在 DataTrigger 中,您需要提供路径为 ComboBox SelectedValue 而不是 PropertyName 的路径。

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>

这篇关于WPF Textblock文本不会在组合框所选项目上动态更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆