简体   繁体   中英

C# WPF How to use custom ComboBox item property in MultiBinding

So, I have a model

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

a combobox with MyModels as ItemSource, where MyModel.Representation defined as displayed property

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

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

now, I'm doing multibinding where i want to refer not to MyModel.Representation, but to MyModel.Id. How to do this?

The only way I know now is

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

But Text contains MyModel.representation. So, how to like this?

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

Assuming you have a ViewModel then you can just bind the ComboBox.SelectedItem to a property and access your Model from there.

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

then in your View ..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM