我努力学习依赖属性和附加属性,所以请原谅我,如果你发现什么,我试图做没有用。WPF附加属性触发两次
我有一个窗口,其DataContext设置到VM,并查看它是含有一个用户控件靶向这一VM一个DataTemplate通常MVVM方法。
我想使窗口容器尽可能愚蠢,因此我试图通过使用附加属性通过usercontrol定义通常驻留在窗口XAML(例如高度)的一些参数。
为了这个目的,我创建了下面的类,我定义的附加属性:
public static class WpfExtensions
{
public static readonly DependencyProperty ContainerHeightProperty = DependencyProperty.RegisterAttached(
"ContainerHeight",
typeof(double),
typeof(WpfExtensions),
new FrameworkPropertyMetadata(300.0, FrameworkPropertyMetadataOptions.AffectsParentArrange | FrameworkPropertyMetadataOptions.AffectsParentMeasure | FrameworkPropertyMetadataOptions.AffectsRender, ContainerHeight)
);
public static void SetContainerHeight(UIElement element, double value)
{
element.SetValue(ContainerHeightProperty, value);
}
public static double GetContainerHeight((UIElement element)
{
return (double)element.GetValue(ContainerHeightProperty);
}
private static void ContainerHeight(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is UserControl)
{
UserControl l_Control = (UserControl)d;
Binding l_Binding = new Binding();
l_Binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Window), 1);
l_Binding.Path = new PropertyPath("Height");
l_Binding.Mode = BindingMode.OneWayToSource;
BindingOperations.SetBinding(d, e.Property, l_Binding);
}
}
}
你可以看到,实现了容器窗口的高度,我在代码中创建从附加绑定的控制属性直至容器窗口。
然而ContainerHeight变化会被解雇的两倍。我第一次从300(默认)变为1024(在XAML中定义的)。然后我立即收到从1024回到300的另一个,我不明白为什么。
窗口代码非常简单:
<Window x:Class="WpfApplication.DialogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lcl="clr-namespace:WpfApplication"
Title="DialogWindow">
<Window.Resources>
<DataTemplate DataType="{x:Type lcl:Dialog_VM}">
<lcl:Dialog_VM_View />
</DataTemplate>
</Window.Resources>
<ContentPresenter Content="{Binding }" />
</Window>
最后简单的视图模型
<UserControl x:Class="WpfApplication.Dialog_VM_View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:lcl="clr-namespace:WpfApplication"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
lcl:WpfExtensions.ContainerHeight="1024">
<StackPanel>
<TextBlock Text="This is a test" />
</StackPanel>
</UserControl>
哪里是你的'ContainerHeight'房产吗? – Bojje
WpfExtensions,我粘贴的第一段代码,与UserControl一起使用,我粘贴的第三段代码。 – user1464603
而不是这种奇怪的方法,你是否考虑简单地设置窗口的SizeToContent属性? – Clemens