gpt4 book ai didi

c# - 显示用户控件而不是文本 MVVM 的组合框

转载 作者:行者123 更新时间:2023-12-03 10:37:42 26 4
gpt4 key购买 nike

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

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

enter image description here

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

这是 XAML 代码。

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

这是 View 模型。
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.
}

最佳答案

要回答您的问题,您的 LauncherView 之间似乎没有任何联系。类(class)和你的ICustomInterface收藏。 @Farzi 正确评论您的 Title属性应该在 ICustomInterface 中声明接口(interface),如果您希望能够从 ICustomInterface 访问它目的。

要解决此问题,请添加 Title属性进入ICustomInterface界面,或更改您的Modules的类型集合到实现 Title 的任何类型属性(property)。

Personal thoughts on your setup:



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

您可以只使用 string 的集合,而不是那样做。 s 代表每个 UserControl 的标题然后绑定(bind)到 ComboBox.SelectedItem属性(property)。然后,您可能只有一个 ICustomInterface 类型的属性。您可以从 SelectedItem 更新属性发生变化时。

在 WPF 中,我们通常使用数据而不是 UI 控件。因此,更好的选择是操作每个 View 的 View 模型,并在 ContentControl 中显示 View 模型。 , 设置了一些 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();
}
}

或者您可以拥有一组 View 模型(浪费资源):
public string SelectedTitle
{
get { return selectedTitle; }
set
{
selectedTitle = value;
NotifyPropertyChanged("SelectedTitle");
ViewModel = ViewModelCollection.Where(v => v.Title == SelectedTitle);
}
}

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

关于c# - 显示用户控件而不是文本 MVVM 的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19268414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com