[英]How to disable combox dropdown when user enters text into the combox
[英]Combox showing User control instead of text MVVM
我有一個用戶控件列表。 我只想一次只顯示一個。 為此,我使用ComboBox顯示用戶控件列表。 並根據所選的ComboBox項目顯示它們。 我創建了一個Custom接口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.
}
為了回答您的問題, LauncherView
類與ICustomInterface
集合之間似乎沒有任何聯系。 @Farzi正確地評論說,如果您希望能夠從ICustomInterface
對象訪問它,則應該在ICustomInterface
接口中聲明您的Title
屬性。
若要解決此問題,請將Title
屬性添加到ICustomInterface
接口,或將Modules
集合的類型更改為實現Title
屬性的任何類型。
您對設置的個人想法:
我個人認為,在ComboBox.ItemsSource
中具有UserControl
對象的集合不是一個好主意。 即使只顯示其中一個,您也將消耗所有這些資源所需的所有資源。
不必那樣做,您可以只使用表示每個UserControl
標題的string
集合,然后綁定到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);
}
}
我確實知道您沒有要求我提出任何個人想法,希望它們能以某種方式為您提供幫助。 抱歉,如果不受歡迎的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.