c# - 正确处理 WPF UserControl 上的控件

标签 c# wpf user-controls

我有一个包含五个条目和五个用户控件的 ComboBox。

当我选择 ComboBox Entry 时,我想将第一个 UserControl 分配给我的网格。 在第二个 ComboBox 条目上,在第二个 UserControl 上,在第三个条目上……依此类推。

现在每个 UserControl 包含一堆控件,例如 TextControl、ComboBox 和 CheckBox。

让我们想象一下下面的伪代码:

combobox_SelectedIndexChanged()
{
    if(comboBox.SelectedIndex == 1)
       grid.Content = new UserControlOne();
    else if(comboBox.SelectedIndex == 2)
       grid.Content = new UserControlTwo();
    else if(comboBox.SelectedIndex == 3)
       grid.Content = new UserControlThree();
    [...]
}

单击按钮时,我想获取分配控件的值,但我不知道如何访问 UserControl。

buttonSave_click()
{
    //TODO: Get Values of a UserControl and assign it to the Model-Class    
}

如何访问 UserControl 的控件并获取它们的值?

最佳答案

就个人而言,我会使用 MVVM 设计模式做这样的事情

ComboBox将绑定(bind)到 ViewModel 的集合或 Model对象

所以你会有

<ComboBox ItemsSource="{Binding SomeCollection}" 
          SelectedItem="{Binding SelectedViewModel}"
          DisplayMemberPath="DisplayName" />

哪里SomeCollectionobject 的集合在你的 ViewModel , 和 SelectedViewModel是一个 object保存所选项目的属性

SomeCollection = new ObservableCollection<object>();
SomeCollection.Add(new ViewModelA());
SomeCollection.Add(new ViewModelB());
SomeCollection.Add(new ViewModelC());
SomeCollection.Add(new ViewModelD());
SomeCollection.Add(new ViewModelE());

SelectedViewModel = SomeCollection[0];

现在您的 SaveCommand可以访问使用 SelectedViewModel 选择的任何内容并根据 typeof(SelectedViewModel 将其转换为适当的类型)

我个人会使用像 IViewModel 这样的通用接口(interface)而不是 object ,并让它包含一些通用属性(例如 DisplayName )和方法。根据您的功能,您甚至可以让它包含自己的保存逻辑,因此您可以在保存命令中执行:

SelectedViewModel.Save();

至于显示正确的 View /用户控件,我会使用 ContentControl , 它是 Content绑定(bind)到您的 SelectedViewModel , 并使用隐式数据模板告诉 WPF 如何绘制每个对象

<ContentControl Content="{Binding SelectedViewModel}">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type local:ViewModelA}">
            <local:UserControlA />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelB}">
            <local:UserControlB />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelC}">
            <local:UserControlC />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelD}">
            <local:UserControlD />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelE}">
            <local:UserControlE />
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

关于c# - 正确处理 WPF UserControl 上的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10952254/

相关文章:

c# - 从用户控件调用父页面上的方法

.net 4.5 中可绑定(bind)的 WPF Richtextbox

wpf - 在WPF中,如何在DataGrid上显示AdornerLayer

c# - WPF如何获得最大化/最小化按钮图标 - 自定义标题栏

c# - 用户控件运行时宽度和高度

C# 调试包含 lambda 表达式的函数

c# - .net 项目和设计器文件的属性错误被锁定

c# - 使用串行端口和 ReadAsync 超时的正确方法

c# - 如何比较两个数据表的单元格值

WPF:带有 2 个(或更多!)ContentPresenters 的模板或 UserControl 以在 'slots' 中呈现内容