继电器命令 命令参数
Posted
技术标签:
【中文标题】继电器命令 命令参数【英文标题】:Relay Commands Command Parameter 【发布时间】:2022-01-17 22:18:50 【问题描述】:我正在尝试在使用 C# 的小型 WPF 项目中使用 MVVM 原则。
我有一个ListBox
,其中填充了CheckBox
es,这是通过绑定回ViewModel而创建的。我还有一个绑定到CheckBox
es 的命令,并希望将CheckBox
es Content
作为CommandParameter
传递。我正在寻找这样的东西:
<Binding ElementName="" Path="Content"/>
很遗憾,因为CheckBox
es 是通过绑定创建的,所以我没有元素名称。
ListBox
/ ListBoxItem
Style
的代码是这样的:
<Style x:Key="CheckBoxListStyle" TargetType="x:Type ListBox">
<Setter Property="SelectionMode" Value="Multiple"></Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="x:Type ListBoxItem" >
<Setter Property="Margin" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="x:Type ListBoxItem">
<CheckBox Command="Binding SelectedItemCommand, Mode=OneWay, Source=StaticResource comd">
<CheckBox.CommandParameter>
<MultiBinding Converter="StaticResource cv">
<Binding ElementName="" Path="Content"/>
<Binding ElementName="" Path="IsChecked"/>
</MultiBinding>
</CheckBox.CommandParameter>
<ContentPresenter></ContentPresenter>
</CheckBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
它的实现是:
<ListBox Grid.Row="1" Style="StaticResource CheckBoxListStyle" Name="lstProducts" ItemsSource="Binding stampInfo, Mode=OneWay, Source=StaticResource vmStamp"
DisplayMemberPath="Country" >
</ListBox>
最终我的目标是能够在文本框中显示所有选定项目的文本Content
s(在这种情况下为国家/地区),每个国家/地区用逗号分隔。我目前唯一缺少的是Country
。
【问题讨论】:
您能否在使用绑定的位置显示您的CheckBox
es 的代码?
@thatguy。感谢您的回复,我已修改问题以包含请求的绑定。
【参考方案1】:
当您真的想以不同方式显示您的数据项时,不要为ListBoxItem
创建ControlTemplate
,而是使用DataTemplate
,这正是它的目的。见Data Templating Overview。
从ListBox
中删除DisplayMemberPath
,因为您不能同时使用路径和自定义DataTemplate
。如果没有DataTemplate
,您只会设置此路径,但您想指定要显示的具体属性或属性路径。
<ListBox Grid.Row="1"
Style="StaticResource CheckBoxListStyle" Name="lstProducts"
ItemsSource="Binding stampInfo, Mode=OneWay, Source=StaticResource vmStamp"/>
将ControlTemplate
替换为DataTemplate
为ItemTemplate
。然后将Content
和CommandParameter
绑定到属性Country
。数据上下文自动设置为绑定的数据项集合中的相应项。 IsChecked
属性可以使用RelativeSource
绑定,即CheckBox
本身。
<Style x:Key="CheckBoxListStyle" TargetType="x:Type ListBox">
<Setter Property="SelectionMode" Value="Multiple"></Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="x:Type ListBoxItem" >
<Setter Property="Margin" Value="2" />
</Style>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<CheckBox Content="Binding Country"
Command="Binding SelectedItemCommand, Mode=OneWay, Source=StaticResource comd">
<CheckBox.CommandParameter>
<MultiBinding Converter="StaticResource cv">
<Binding Path="Country"/>
<Binding Path="IsChecked" RelativeSource="RelativeSource Self"/>
</MultiBinding>
</CheckBox.CommandParameter>
</CheckBox>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
另一种选择是创建具有可以绑定到CheckBox
的IsChecked
属性的属性的数据项。然后您可以在数据项的设置器中或在例如执行命令的按钮单击,该命令会过滤视图模型中的绑定集合以查找已检查的项目。
【讨论】:
非常感谢。非常感谢您的帮助和解决方案。以上是关于继电器命令 命令参数的主要内容,如果未能解决你的问题,请参考以下文章