我的 ViewModel 中有一個 UserControl,需要根據我的 ViewModel 的背景關系進行更改。
例如:我的 ViewModel 包含一個列舉。當此列舉的值為 時Test1,CurrentView 屬性將更改為型別的物件MyCustomTest1。當值為 時Test2,該屬性成為 的物件MyCustomTest2。我已經知道如何實作這一點,但不知道如何告訴我的 UI 呈現 CustomControl。
我想我需要為此使用 ItemsControl,但我不確定。這是我到目前為止所嘗試的。
<StackPanel x:Name="MainContent" Grid.Column="1">
<ItemsControl ItemsSource="{Binding CurrentView, Mode=OneWay}" />
</StackPanel>
我的自定義組件只包含一個帶有 TextBlock 的 StackPanel。
我的自定義測驗 1:
<StackPanel>
<TextBlock>Hello World</TextBlock>
</StackPanel>
當 CurrentView 更新時,我的 ViewModel 呼叫 INotifyPropertyChanged。
public UserControl CurrentView
{
get => currentView;
private set
{
currentView = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentView)));
}
}
有誰知道如何實作這一目標?
uj5u.com熱心網友回復:
視圖模型必須永遠不知道任何控制元件。控制元件僅在視圖中處理。
您的問題通常通過使用資料模型和關聯的 來解決DataTemplated,它指示視圖如何呈現資料模型。
這意味著您應該為每個視圖引入一個資料模型。然后將此模型系結到一個ContentControl. 然后ContentControl將應用DataTemplate模型的資料型別并渲染視圖。
主視圖模型.cs
class MainViewModel : INotifyPropertyChanged
{
// TODO::Let this property raise the PropertyChanged event
public object CurrentViewModel { get; set; }
private void LoadView()
{
this.CurrentView = new MyCustomControlViewModel();
}
}
主視窗.xaml
<Window>
<Window.DataContext>
<MainViewModel />
</Window.Resources>
<Window.Resources>
<DataTemplate DataType="{x:Type MyCustomControlViewModel}">
<MyCustomControl />
</DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding CurrentViewModel}" />
</Window>
uj5u.com熱心網友回復:
您可以設計一個 ValueConverter,例如:
using System;
using System.Globalization;
using System.Windows.Data;
public class MyValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is ControlType type)
{
if (type == ControlType.Type1)
return new MyCustomTest1();
else if (type == ControlType.Type2)
return new MyCustomTest2();
}
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后你可以添加一個ContentControl,并將其系結Content到列舉屬性,并引入轉換器:
<UserControl.Resources>
<!-- vc is the namespace where you put the value converter class -->
<vc:MyValueConverter x:Key="converter" />
</UserControl.Resources>
...
<ContentControl Content="{Binding CurrentView, Converter={StaticResource converter}}" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452450.html
上一篇:<EventTriggerRoutedEvent="Binding.TargetUpdated">未使用ContentTemplateSelector觸發
