Mer*_*ham 22 wpf mvvm radio-button ivalueconverter
我以前把枚举绑定到单选按钮,我一般都明白它是如何工作的.我使用了这个问题的替代实现:如何将RadioButtons绑定到枚举?
我想生成一个自定义类型的运行时枚举集,而不是枚举,而是将它们作为一组单选按钮呈现.我已经得到了一个视图,它使用一个运行时枚举的集合ListView
,并绑定到ItemsSource
和SelectedItem
属性,因此我ViewModel
可以正确连接.现在我正试图从a切换ListView
到a ItemsControl
与单选按钮.
就我而言:
<Window.Resources>
<vm:InstanceToBooleanConverter x:Key="InstanceToBooleanConverter" />
</Window.Resources>
<!-- ... -->
<ItemsControl ItemsSource="{Binding ItemSelections}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type vm:ISomeType}">
<RadioButton Content="{Binding Name}"
IsChecked="{Binding Path=SelectedItem, Converter={StaticResource InstanceToBooleanConverter}, ConverterParameter={Binding}}"
Grid.Column="0" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
InstanceToBooleanConverter
具有与EnumToBooleanConverter
其他问题相同的实现.这似乎是正确的,因为它似乎只是调用Equals
方法:
public class InstanceToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在遇到的问题是我无法弄清楚如何发送运行时值ConverterParameter
.当我尝试(使用上面的代码)时,我收到此错误:
无法在"绑定"类型的"ConverterParameter"属性上设置"绑定".'绑定'只能在DependencyObject的DependencyProperty上设置.
有没有办法绑定到项目实例,并将其传递给IValueConverter
?
Mer*_*ham 36
事实证明,放弃使用ItemsControl
并转而使用它要简单得多ListBox
.
它可能更重,但这主要是因为它正在为你做繁重的工作.在RadioButton.IsChecked
和之间进行双向绑定真的很容易ListBoxItem.IsSelected
.通过适当的控制模板ListBoxItem
,您可以轻松摆脱所有选择的视觉效果.
<ListBox ItemsSource="{Binding Properties}" SelectedItem="{Binding SelectedItem}">
<ListBox.ItemContainerStyle>
<!-- Style to get rid of the selection visual -->
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:SomeClass}">
<RadioButton Content="{Binding Name}" GroupName="Properties">
<!-- Binding IsChecked to IsSelected requires no support code -->
<RadioButton.IsChecked>
<Binding Path="IsSelected"
RelativeSource="{RelativeSource AncestorType=ListBoxItem}"
Mode="TwoWay" />
</RadioButton.IsChecked>
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18574 次 |
最近记录: |