我在WPF应用程序页面上有多个扩展器。我想将一个扩展器触发的动作重复到其他扩展器。即,在一个扩展器发生扩展事件时,所有其他扩展器也应扩展。同样会崩溃。任何代码片段的想法将不胜感激。
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Expander Grid.Row="0" IsExpanded="True">
<Expander.Header>
Expander 1
</Expander.Header>
<Expander.Content>
This is first Expander
</Expander.Content>
</Expander>
<Expander Grid.Row="1" IsExpanded="True">
<Expander.Header>
Expander 2
</Expander.Header>
<Expander.Content>
This is Second Expander
</Expander.Content>
</Expander>
</Grid>
答案 0 :(得分:1)
这可以通过几种方法来解决。最好的方法是在viewmodel中设置一个属性,并将所有扩展器链接到该属性。
检查以下代码:
IsExpanded="{Binding ExpandAll, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
完整的代码如下:
MainWindow.xaml
<Window x:Class="SOF.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SOF"
mc:Ignorable="d"
Title="Window2" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Expander Grid.Row="0" IsExpanded="{Binding ExpandAll, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" >
<Expander.Header>
Expander 1
</Expander.Header>
<Expander.Content>
This is first Expander
</Expander.Content>
</Expander>
<Expander Grid.Row="1" IsExpanded="{Binding ExpandAll, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}">
<Expander.Header>
Expander 2
</Expander.Header>
<Expander.Content>
This is Second Expander
</Expander.Content>
</Expander>
</Grid>
</Window>
MainWindow.cs
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
ExpanderViewModel evm = new ExpanderViewModel();
this.DataContext = evm;
}
}
}
ViewModel.cs
public abstract class ObservableModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propname = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
public ObservableModel() { }
}
public class ExpanderViewModel: ObservableModel
{
private bool mExpandAll;
public bool ExpandAll
{
get { return mExpandAll; }
set { mExpandAll = value; OnPropertyChanged(); }
}
public ExpanderViewModel() { }
}