更改列表选择的用户控制

我是WPF的新手,并且在选择相应的listviewitem时尝试动态显示用户控件。 我看了下面的问题

WPF:根据相应的ViewModels(MVVM)切换UserControls

使用WPF / MVVM在运行时动态更改UserControl内容

动态用户控件更改 – WPF

所有的问题都提到了我不认为我正在使用的MVVM,或者我是不是在不知不觉中。

为了更好地解释我想要做什么,我在左侧有一个带有列表视图的窗口,在右侧我想根据列表中的哪个项目选择动态显示用户控件。

我需要添加到XAML以在用户控件1和用户控件2之间进行选择? 我需要在“on selection action”代码中添加哪些代码来更改用户控件。

窗户

                          

用户控制1

              

用户控制2

              

用户控件的* .xaml.cs文件为空。

您需要做的就是处理ListView对象的SelectionChanged:

                          

我还命名了你的根网格。 这里的代码背后:

  private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { dgRoot.Children.Clear(); UserControl control = null; if () { control = new UserControl1(); } else { control = new UserControl2(); } control.SetValue(Grid.ColumnProperty, 2); this.dgRoot.Children.Add(control); } 

添加:如果您不确定GC将收集不需要的对象,您可以将此控件添加为类的字段并在构造函数中初始化它们:

 public partial class ProfileWindow : Window { UserControl control1, control2; // or if you want the exact types: // UserControl1 control1; // UserControl2 control2; public ProfileWindow() { control1 = new UserControl1(); control2 = new UserControl2(); } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if () //then you want to add UserControl1 instance { if (!dgRoot.Children.Contains(control1)) { dgRoot.Children.Clear(); control1.SetValue(Grid.ColumnProperty, 2); this.dgRoot.Children.Add(control1); } } else //else you want to add UserControl2 instance { if (!dgRoot.Children.Contains(control2)) { dgRoot.Children.Clear(); control2.SetValue(Grid.ColumnProperty, 2); this.dgRoot.Children.Add(control2); } } } } 

附加2:你可以走得更远。 如果你有N个UserControls,其中N是可变的,你可以创建包含所有控件的Dictionary:

 public partial class ProfileWindow : Window { private Dictionary SettingsControls; public ProfileWindow() { SettingsControls = new Dictionary(); SettingsControls.Add(, new UserControl1()); SettingsControls.Add(, new UserControl2()); // and you can add any controls you want. // in this example SettingsObject is type of items that are in the ListView. // so, if your "Settings" object contains only strings, your dictionary can be Dictionary. // if SettingsObject is custom object, you have to override GetHash() and Equals() methods for it } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var item = SettingsList.SelectedItem is SettingsObject; if (item == null) return; if (SettingsControls.ContainsKey(item) && !dgRoot.Children.Contains(SettingsControls[item])) { dgRoot.Children.Clear(); SettingsControls[item].SetValue(Grid.ColumnProperty, 2); dgRoot.Children.Add(SettingsControls[item]); } else { /*handle it if you want*/} } } }