我有一个关于WPF样式的问题。 让我们使用类(或准备这样的类)来包含DependencyProperty。
public class MyProperty : DependencyObject
{
public static readonly DependencyProperty exampleValueProperty = DependencyProperty.Register("exampleValue", typeof(bool), typeof(MyProperty));
public bool exampleValue
{
get { return (bool)this.GetValue(exampleValueProperty); }
set { this.SetValue(exampleValueProperty, value); }
}
}
public class MyTextBlock : TextBlock
{
public static readonly DependencyProperty myPropertyProperty= DependencyProperty.Register(
"myProperty", typeof(MyProperty), typeof(MyTextBlock));
public MyProperty myProperty
{
get
{
return (MyProperty)this.GetValue(myPropertyProperty);
}
set
{
this.SetValue(myPropertyProperty, value);
}
}
}
现在在XAML文件中定义样式,并在我的主窗口网格上放置两个MyTextBlock类的对象:
<Window x:Class="WpfApplication1.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:WpfApplication1"
xmlns:custom="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<Style TargetType="{x:Type custom:MyTextBlock}">
<Setter Property="Background" Value="Aqua" />
<Setter Property="myProperty">
<Setter.Value>
<custom:MyProperty exampleValue="true" />
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid RenderTransformOrigin="0.514,0.47" Margin="100,0,0,0">
<custom:MyTextBlock x:Name="textBlock1" Height="80" Width="80" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,104,62.8,0" />
<custom:MyTextBlock x:Name="textBlock2" Height="80" Width="80" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,200,62.8,0" />
</Grid>
</Window>
现在的问题是,当我使用以下代码将exampleValue更改为false时:
textBlock1.myProperty.exampleValue = false;
exampleValue也会被textBlock2更改。
我发现,textBlock1.myProperty和textBlock2.myProperty返回的hashCode是相同的。可能是因为我们首先创建了一个myProperty对象,然后Setter只是将其(副本)分配给每个MyTextBlock对象。有没有办法在这里使用克隆?这样每个对象都会有自己的“myProperty”吗?
我知道如果我按对象定义我的属性,这个方法会正确工作(但看起来像是一种解决方法而不是解决方案):
<custom:MyTextBlock x:Name="textBlock1" Height="80" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,104,62.8,0">
<custom:MyTextBlock.myProperty>
<custom:MyProperty exampleValue="False"/>
</custom:MyTextBlock.myProperty>
</custom:MyTextBlock>
<custom:MyTextBlock x:Name="textBlock2" Height="80" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,200,62.8,0">
<custom:MyTextBlock.myProperty>
<custom:MyProperty exampleValue="False"/>
</custom:MyTextBlock.myProperty>
</custom:MyTextBlock>
MyProperty
设置为Freezable
,这样当您在代码中更改值时,就会被强制创建一个新的属性实例。 - grek40