我见过其他问题非常相似,但不知何故,我仍然无法得到它的工作。这是场景。绑定RadioButton IsChecked到ListBoxItem IsSelected和ListBox IsFocused
我有什么 我有一个ListBox
显示我的视图模型的列表。每个视图模型都有一个显示在另一个嵌套列表框中的子项列表。我正在使用DataTemplate
来实现此目的。
我想要的东西 我想孩子们的项目有选择ListBoxItem
时选择一个RadioButton
当ListBox
具有焦点(内部ListBox
)。
目前,上述IsSelected
部分工作得很好,但是当我从一个视图模型移动到另一个视图模型时(即第一个ListBox失去焦点),第一个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
,但wasnt工作要么。有什么建议么?
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();
}
}
这样做的IsSelected
部分的伟大工程,即只有在列表中的一个项目都有随时选择的单选按钮。但是,当控制失去焦点时,所选项目的单选按钮仍处于选中状态(不是我想要的)。
对不起,我读过你试过MultiBinding AFTER回答。你介意解释你是如何做到的? – Carlo 2009-08-28 22:15:38