我见过其他与此非常相似的问题,但不知何故我仍然无法让它发挥作用。这是场景。
我拥有的我有一个ListBox
显示我的视图模型的列表。每个视图模型都有一个子级列表,这些子级显示在另一个嵌套列表框中。我正在使用一个DataTemplate
为了达成这个。
我想要的是我希望儿童用品有一个RadioButton
当ListBoxItem
被选中并且当ListBox
有焦点(内在ListBox
).
目前,IsSelected
上面的部分工作得很好,但是当我从一个视图模型移动到另一个视图模型时(即第一个列表框失去焦点)第一个上的单选按钮ListBox
保持选中状态。
这是代码:
<Style TargetType="{x:Type ListBox}">
<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}">
<RadioButton Focusable="False">
<RadioButton.Style>
<Style TargetType="{x:Type RadioButton}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsFocused, Mode=OneWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}}" Value="False">
<Setter Property="IsChecked" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</RadioButton.Style>
<RadioButton.IsChecked>
<Binding Path="IsSelected" Mode="TwoWay" RelativeSource="{RelativeSource TemplatedParent}" />
</RadioButton.IsChecked>
<ContentPresenter></ContentPresenter>
</RadioButton>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
我也尝试过MultiBinding
,但这也不起作用。有什么建议么?
UPDATE更新以包括我的尝试MultiBinding
:
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<RadioButton>
<RadioButton.IsChecked>
<MultiBinding>
<MultiBinding.Converter>
<DataExportTool:AllTrueConverter/>
</MultiBinding.Converter>
<Binding Path="IsSelected" Mode="TwoWay" RelativeSource="{RelativeSource TemplatedParent}"/>
<Binding Path="IsFocused" Mode="OneWay" RelativeSource="{RelativeSource TemplatedParent}"/>
</MultiBinding>
</RadioButton.IsChecked>
<ContentPresenter/>
</RadioButton>
</ControlTemplate>
和转换器:
public class AllTrueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.Cast<bool>().All(x => x);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return Enumerable.Repeat((bool)value, 2).Cast<object>().ToArray();
}
}
The IsSelected
其中一部分效果很好,即列表中只有一个项目在任何时候都选择了单选按钮。但是,当控件失去焦点时,所选项目的单选按钮仍处于选中状态(不是我想要的)。