【WPF】.NET Framework 4.0对XAML解析的改进——Visual可以作为Setter的Value了

WPF Bug清单12中我们介绍过一个与不同WPF版本上XAML解析相关的Bug。今天要介绍另一个.NET Framework 4对于XAML解析上的改进。

 

我们知道Button属于ContentControlContentControl里的Content逻辑上可以是任何其它Control。所以我们可以把ButtonContent设置为一个Image。这也是一个很常见的功能。

 

代码如下所示:

<Button Height="28">
    
<Image Width="16" Height="16" Source="Green.PNG" Stretch="Fill"/> 
</Button>

 

那么我们可不可以在ButtonStyle里把Content属性就设置为Image呢?理论上应该没有什么问题。但是事实是在.NET Framework 4之前的版本的WPF中,像下面这样:

Button Style With Content Stter
<Style x:Key="ImageButtonStyle" TargetType="{x:Type Button}">
    
<Setter Property="Content">
        
<Setter.Value>
            
<Image Width="16" Height="16" Source="Green.PNG" Stretch="Fill"/> 
        
</Setter.Value>
    
</Setter>
    
<Setter Property="ToolTip">
        
<Setter.Value>
            
<Image Width="16" Height="16" Source="Green.PNG" Stretch="Fill"/>
        
</Setter.Value>
    
</Setter>
</Style>

 

Style中设置ContentToolTip或其它Object的属性为其它的Visual,可以编译过,但是会运行时异常,抛出这样的Exception

 

Unhandled Exception: System.Windows.Markup.XamlParseException: Cannot add content of type 'System.Windows.Controls.Image' to an object of type 'System.Object'.  Error at object 'System.Windows.Controls.Image' in markup file 'ChangeButtonContent;component/mainwindow.xaml' Line 19 Position 12.

 

如果在Blend3打开包含上面Style的文件。会直接显示一个下面这样的错误:

 

“System.Windows.Controls.Image”不是”Setter.Value”的有效值;不支持从VisualContentElement派生的值。

 

Blend3的错误的听上去有别的意思,似乎潜台词就是:这个应该可以这样做,但是现在“不支持”。

 

好消息是:.NET Framework 4.0开始,上面的Style的写法是完全可以正常运行的了。无论是在VS2010还是Blend4中,都不存在问题。

 

希望WPF越来越好。

原文地址:https://www.cnblogs.com/nankezhishi/p/XAMLImproveInDoNet4.html