[英]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 一个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"/>
now, I'm doing multibinding where i want to refer not to MyModel.Representation, but to MyModel.Id. 现在,我正在执行多重绑定,我不想引用MyModel.Representation,而是引用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. 但是Text包含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. 假设您有
ViewModel
则只需将ComboBox.SelectedItem
绑定到属性,然后从那里访问您的Model
。
class ViewModel
{
public MyModel SelectedModel { get; set; }
public ICommand MyCommand => new DelegateCommand(MyCommandMethod);
public void MyCommandMethod()
{
string representation = SelectedModel.Representation;
}
}
then in your View
.. 然后在您的
View
..
<ComboBox Name="MyBox"
ItemsSource="{Binding Source={StaticResource myModelsData}}"
DisplayMemberPath="Representation"
SelectedItem="{Binding SelectedModel}"/>
<Button Command="{Binding MyCommand}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.