【发布时间】:2015-08-20 07:12:12
【问题描述】:
因此,在互联网的帮助下,我建立了不错的 GUI 内容(感谢 Google :)),在 ComboBox 的帮助下,我可以在一个 ContentControl 中的不同 UserControl 之间进行更改。所以因为我对 WPF 很陌生,所以我想我有一些问题要问你们。
当程序启动它的所有视图刷新组合框项目。我可以多次添加相同的视图。 “主”窗口 ViewModel 的代码:
ConfigurationDialog.xaml(主窗口)代码:
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModel:GeneralSettingsViewModel}">
<View:GeneralSettingsView/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:AdvancedSettingsViewModel}">
<View:AdvancedSettingsView/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="ComboBoxMenu" Grid.Column="0" Margin="5" Height="20" ItemsSource="{Binding Settings}" SelectedIndex="0">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Padding="10"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Border Grid.Column="1" Margin="5" BorderBrush="#FF7F9DB9" BorderThickness="1">
<ContentControl Content="{Binding ElementName=ComboBoxMenu, Path=SelectedItem}"/>
</Border>
</Grid>
ConfigurationDialogViewModel 中的代码:
public class ConfigurationDialogViewModel : ViewModelBase
{
private readonly ObservableCollection<SettingsViewModelBase> settings;
public ObservableCollection<SettingsViewModelBase> Settings
{
get { return this.settings; }
}
public ConfigurationDialogViewModel()
{
this.settings = new ObservableCollection<SettingsViewModelBase>();
this.settings.Add(new GeneralSettingsViewModel());
this.settings.Add(new AdvancedSettingsViewModel());
this.settings.Add(new GeneralSettingsViewModel());
}
}
所以我在那里建立了两次“GeneralSettingsViewModel()”,它工作得很好。唯一我不喜欢的是总是同一个名字。就我而言,它显示两次“常规设置”名称。我喜欢有“General Settings 1”和“General Settings 2”等GeneralSettingsViewModel的代码:
public class GeneralSettingsViewModel : SettingsViewModelBase
{
public override string Name
{
get { return "General"; }
}
}
public abstract class SettingsViewModelBase : ViewModelBase
{
public abstract string Name { get; }
}
后者当例如选择“常规设置1”并选择和数据Inneedet时,我喜欢它不再是“常规设置1”可用,因此如何从ComboBox中删除该项目。
因此可以在“主窗口”ViewModel(在我的情况下为“ConfigurationDialogViewModel”)的组合框中手动生成项目名称,以及以后如何删除它?另外,我必须捕获 UserControl 的输入日期。
查看其中一个用户控件:
<UserControl x:Class="ConfigurationDialogExample.View.GeneralSettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBlock Text="General settings" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
如果有任何问题,请提出。抱歉,如果提出“错误”问题(我是 WPF 新手)。
【问题讨论】:
标签: c# wpf mvvm combobox datacontext