【问题标题】:Combox showing User control instead of text MVVM显示用户控件而不是文本 MVVM 的组合框
【发布时间】:2013-10-09 09:41:55
【问题描述】:

我有一个用户控件列表。我想在我的视图中一次只显示一个。为此,我使用 ComboBox 来显示用户控件列表。并根据所选的 ComboBox 项目显示它们。我创建了一个自定义接口 ICustomInterface,它有一个我想向用户显示的 Title 属性。我在我的用户界面上实现了这一点。

但问题是,当我运行我的应用程序时,我看到的不是标题文本,而是 UserControl 本身。

您可以在这里看到整个用户控件都存在于组合框中。我需要做的是显示文本。

这是 XAML 代码。

<ComboBox  Grid.Column="1" ItemsSource="{Binding Modules}" SelectedItem="{Binding SelectedModule}" DisplayMemberPath="{Binding Title}"/>

这是视图模型。

public List<ICustomInterface> Modules
{
    get
    {
         return _modules; // Assume that there are some items present in this.
    }
}

这是我要显示的用户控件的集合。

public partial class LauncherView : UserControl, ICustomInterface
{
    public string Title { get { return "Launcher"; } }

    // User control stuff.
}

【问题讨论】:

  • 标题应该是类型为你的模块的类的一部分,然后只有标题可见

标签: c# wpf mvvm combobox


【解决方案1】:

要回答您的问题,您的 LauncherView 类和您的 ICustomInterface 集合之间似乎没有任何联系。 @Farzi 正确地评论说,如果您希望能够从 ICustomInterface 对象访问您的 Title 属性,则应该在 ICustomInterface 接口中声明它。

要解决此问题,请将Title 属性添加到ICustomInterface 接口中,或者将Modules 集合的类型更改为实现Title 属性的任何类型。

个人对设置的看法:

就个人而言,我认为在ComboBox.ItemsSource 中收集UserControl 对象并不是一个好主意。您将消耗所有所需的所有资源,即使只显示一个。

您可以只使用代表每个UserControl 标题的strings 集合,然后绑定到ComboBox.SelectedItem 属性,而不是那样做。然后,您可以只拥有一个 ICustomInterface 类型的属性,您可以在 SelectedItem 属性更改时对其进行更新。

在 WPF 中,我们通常使用数据而不是 UI 控件。因此,更好的选择是操作每个视图的视图模型,并在 ContentControl 中显示视图模型,首先设置了一些 DataTemplates

<Application.Resources>
    <DataTemplate DataType="{x:Type ViewModels:YourViewModel}">
        <Views:YourView />
    </DataTemplate>
</Application.Resources>

在主视图中:

<ContentControl Content="{Binding ViewModel}" />

在主视图模型或代码后面:

public ICustomInterface ViewModel
{
    get { return viewModel; }
    set { viewModel= value; NotifyPropertyChanged("ViewModel"); }
}

public string SelectedTitle
{
    get { return selectedTitle; }
    set 
    {
        selectedTitle = value; 
        NotifyPropertyChanged("SelectedTitle");
        if (SelectedTitle == "Something") ViewModel = new SomethingViewModel();
        if (SelectedTitle == "Other") ViewModel = new OtherViewModel();
    }
}

或者您可以拥有一组视图模型(浪费资源):

public string SelectedTitle
{
    get { return selectedTitle; }
    set 
    {
        selectedTitle = value; 
        NotifyPropertyChanged("SelectedTitle");
        ViewModel = ViewModelCollection.Where(v => v.Title == SelectedTitle);
    }
}

我明白您并没有询问我的任何个人想法,我希望他们在某种程度上对您有所帮助。如果他们不受欢迎,我们深表歉意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多