【问题标题】:C# WPF How to use custom ComboBox item property in MultiBindingC# WPF 如何在 MultiBinding 中使用自定义 ComboBox 项属性
【发布时间】:2018-06-16 07:12:42
【问题描述】:

所以,我有一个模型

public class MyModel
    {
        public string Id { get; }
        public string Representation { get; }
        public static IEnumerable<MyModel> MyModels() { ... }
    }

以 MyModels 作为 ItemSource 的组合框,其中 MyModel.Representation 定义为显示属性

<ObjectDataProvider x:Key="myModelsData" 
                    ObjectType="{x:Type models:MyModel}" 
                    MethodName="MyModels"/>

<ComboBox Name="MyBox" 
          ItemsSource="{Binding Source={StaticResource myModelsData}}" 
          DisplayMemberPath="Representation"/>

现在,我正在执行多重绑定,我不想引用 MyModel.Representation,而是引用 MyModel.Id。如何做到这一点?

我现在唯一知道的方法是

<Button Command="{Binding MyCommand}">
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource myModelConverter }">
            <Binding ElementName="MyBox" Path="Text"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

但 Text 包含 MyModel.representation。那么,如何喜欢呢?

<Binding Path={MyBox.SelectedItem.Id}/>

【问题讨论】:

    标签: c# wpf data-binding combobox


    【解决方案1】:

    假设您有一个ViewModel,那么您只需将ComboBox.SelectedItem 绑定到一个属性并从那里访问您的Model

    class ViewModel
    {
        public MyModel SelectedModel { get; set; }
        public ICommand MyCommand => new DelegateCommand(MyCommandMethod);
        public void MyCommandMethod()
        {
            string representation = SelectedModel.Representation;
        }
    }
    

    然后在你的View..

    <ComboBox Name="MyBox"
              ItemsSource="{Binding Source={StaticResource myModelsData}}"
              DisplayMemberPath="Representation"
              SelectedItem="{Binding SelectedModel}"/>
    <Button Command="{Binding MyCommand}" />
    

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多