dec*_*one 29
试试下面的代码:
<StackPanel Name="StackPanel1">
<StackPanel.Resources>
<local:ExpanderToBooleanConverter x:Key="ExpanderToBooleanConverter" />
</StackPanel.Resources>
<Expander Header="Expander 1"
IsExpanded="{Binding SelectedExpander, Mode=TwoWay, Converter={StaticResource ExpanderToBooleanConverter}, ConverterParameter=1}">
<TextBlock>Expander 1</TextBlock>
</Expander>
<Expander Header="Expander 2"
IsExpanded="{Binding SelectedExpander, Mode=TwoWay, Converter={StaticResource ExpanderToBooleanConverter}, ConverterParameter=2}">
<TextBlock>Expander 2</TextBlock>
</Expander>
<Expander Header="Expander 3"
IsExpanded="{Binding SelectedExpander, Mode=TwoWay, Converter={StaticResource ExpanderToBooleanConverter}, ConverterParameter=3}">
<TextBlock>Expander 3</TextBlock>
</Expander>
<Expander Header="Expander 4"
IsExpanded="{Binding SelectedExpander, Mode=TwoWay, Converter={StaticResource ExpanderToBooleanConverter}, ConverterParameter=4}">
<TextBlock>Expander 4</TextBlock>
</Expander>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
public class ExpanderToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value == parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (System.Convert.ToBoolean(value)) return parameter;
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
public class ExpanderListViewModel
{
public Object SelectedExpander { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
StackPanel1.DataContext = new ExpanderListViewModel();
Run Code Online (Sandbox Code Playgroud)
在XAML中,我们有4个扩展器.他们都继承ViewModel(类型ExpanderListViewModel从容器)StackPanel通过DataContext.
它们都绑定到ViewModel类上的单个属性.并且已经ConverterParameter在绑定中为自己定义了唯一索引.SelectedExpander每当展开扩展器时,该索引都会保存在属性中.并使用该索引,如果存储的索引与给定的索引匹配,并且存储的索引不匹配,则Converter返回.truefalse
放入断点Convert和类的ConvertBack方法,Converter你会看到发生了什么.