WPF自定義控件可跟蹤視圖模型子屬性更改以自動重新提交自身嗎?WPF自定義控件重新渲染視圖模型子屬性更改
比方說,我有兩個屬性的模型:
public class FullName : ViewModel
{
string _first;
string _last;
public string First
{
get { return _first; }
set
{
_first = value;
RaisePropertyChanged();
}
}
public string Last
{
get { return _last; }
set
{
_last = value;
RaisePropertyChanged();
}
}
}
其中ViewModel
是:
public abstract class ViewModel : INotifyPropertyChanged
{
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) =>
PropertyChanged?.Invoke(this, e);
public event PropertyChangedEventHandler PropertyChanged;
}
我想對WPF自定義控件依賴屬性(AffectsRender
,無SubPropertiesDoNotAffectRender
)以這種方式參照模型,使得控制在First
和Last
屬性變化上自動重投:
public class Tag : Control
{
public static readonly DependencyProperty FullNameProperty =
DependencyProperty.Register("FullName", typeof(FullName), typeof(Tag),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public FullName FullName
{
get { return (FullName)GetValue(FullNameProperty); }
set { SetValue(FullNameProperty, value); }
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
if (FullName == null)
return;
FontFamily courier = new FontFamily("Courier New");
Typeface courierTypeface = new Typeface(courier, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText ft2 = new FormattedText(FullName.First + " " + FullName.Last,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
courierTypeface,
14.0,
Brushes.Black);
drawingContext.DrawText(ft2, new Point());
}
}
下面是測試它的片斷:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="139.9" Width="249.514">
<StackPanel>
<StackPanel.DataContext>
<local:FullName>
<local:FullName.First>John</local:FullName.First>
<local:FullName.Last>Doe</local:FullName.Last>
</local:FullName>
</StackPanel.DataContext>
<local:Tag FullName="{Binding}" Height="20"/>
<TextBox Text="{Binding First, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding Last, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Window>
不幸的是,這是行不通的 - 更改不會傳播到自定義控制。它可以有效地完成嗎?那麼SubPropertiesDoNotAffectRender
是什麼?
@nkoniishvt其實,請看看'標籤。 OnRender',繪製'FullName.First +「」+ FullName.Last'。我需要的是完全「所有者繪製的」圖表組件(不涉及模板或繼承)來顯示動態可更新視圖模型對象圖的內容。我得到了一個印象,即控制跟蹤模型子屬性的變化沒有'SubPropertiesDoNotAffectRender'顯式抑制,但它不起作用。 –