我有兩個類 A 和 B,它們都實作了 IThingWithList 介面。
public interface IThingWithList
{
ObservableCollection<int> TheList;
}
A 中的串列包含 1、2、3 B 中的串列包含 4、5、6
我有一個控制器類,它有一個包含 A 和 B 的 IThingWithList 串列
public class MyControllerClass
{
public ObservableCollection<IThingWithList> Things { get; } = new ObservableCollection<IThingWithList>() { A, B };
public IThingWithList SelectedThing { get; set; }
}
現在,在 xaml 我有兩個 ComboBoxes 如下
<ComboBox
ItemsSource="{Binding MyController.Things}"
SelectedValue="{Binding MyController.SelectedThing, Mode=TwoWay}" />
<ComboBox
DataContext="{Binding MyController.SelectedThing}"
ItemsSource="{Binding TheList}" />
第一個 ComboBox 控制哪個(A 或 B)是第二個組合框的資料背景關系。
問題:
當我從第一個 ComboBox 中選擇 A 或 B 時,第二個 ComboBox 的串列項不會更新。
我試過的:
制作 A 和 B ObservableObjects
使 IThingWithList 實作 INotifyPropertyChanged
將 UpdateSourceTrigger 添加到 ItemsSource 系結
搜索谷歌。
uj5u.com熱心網友回復:
以下是我通常如何執行 ViewModel(在您的情況下為“控制器”)基類以獲得您正在尋找的功能:
這是所有 VM 派生的基類。
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void SetAndNotify<T>(ref T property, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(property, value))return;
property = value;
this.OnPropertyChanged(propertyName);
}
}
以下是我將如何調整您的 ControllerClass:
public class MyControllerClass : ViewModelBase
{
private ObservableCollection<IThingWithList> _things;
public ObservableCollection<IThingWithList> Things
{
get => _things;
set { SetAndNotify(ref _things, value); }
}
private IThingWithList _selectedthing;
public IThingWithList SelectedThing
{
get => _selectedThing;
set{SetAndNotify(ref _selectedThing, value);}
}
}
現在調整您的 XAML 以設定容器的 DataContext 而不是每個控制元件(讓生活更輕松)
<UserControl xmlns:local="clr-namespace:YourMainNamespace">
<UserControl.DataContext>
<local:MyControllerClass/>
</UserControl.DataContext>
<StackPanel>
<ComboBox
ItemsSource="{Binding Things}"
SelectedValue="{Binding SelectedThing, Mode=TwoWay}" />
<!-- ComboBox ItemsSource="See next lines" /-->
</StackPanel>
</Window>
您可以更改SelectedThing為 ObservableCollection 或者您可以擁有第二個物件,即串列并相應地更新:
//Add into MyControllerClass
public MyInnerThingList => SelectedThing.TheList;
//Edit the SelectedThing to look like:
private IThingWithList _selectedthing;
public IThingWithList SelectedThing
{
get => _selectedThing;
set
{
SetAndNotify(ref _selectedThing, value);
RaisePropertyChanged(nameof(MyInnerThingList));
}
}
然后將系結更改為:
<ComboBox ItemsSource="{Binding MyInnerThingList, Mode=OneWay}" />
您可能還想添加 SelectedMyInnerThing 屬性,但不確定是否需要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/408089.html
標籤:
