这困扰了我一段时间,我厌倦了解决这个问题.在WPF中,涉及到的"操作顺序"是什么:
所有这些都考虑了嵌套控件和模板(当应用模板时).
我有很多有问题的场景,但这只是一个例子:
自定义用户控件
<UserControl x:Class="UserControls.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<StackPanel>
<Label Content="{Binding Label1}" />
<Label Content="{Binding Label2}" />
</StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
用户控制代码隐藏
using System;
using System.Windows;
using System.Windows.Controls;
namespace UserControls
{
public partial class TestUserControl : UserControl
{
public static readonly DependencyProperty Label1Property = DependencyProperty.Register("Label1", typeof(String), typeof(TestUserControl), new FrameworkPropertyMetadata(OnLabel1PropertyChanged));
public String Label1
{
get { return (String)GetValue(Label1Property); }
set { SetValue(Label1Property, value); }
}
public static readonly DependencyProperty Label2Property = DependencyProperty.Register("Label2", typeof(String), typeof(TestUserControl), new FrameworkPropertyMetadata(OnLabel2PropertyChanged));
public String …Run Code Online (Sandbox Code Playgroud) 我只是潜入WPF并发现这有点奇怪而且让我的风格感到沮丧:为什么某些东西的价值可能是资源,但你不能直接将值设置为资源所代表的东西?例:
这是有效的:
<ToggleButton>
<ToggleButton.Resources>
<Image x:Key="cancelImage" Source="cancel.png" />
</ToggleButton.Resources>
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Content" Value="{DynamicResource cancelImage}" />
</Style>
</ToggleButton.Style>
</ToggleButton>
Run Code Online (Sandbox Code Playgroud)
但这不是:
<ToggleButton>
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Content">
<Setter.Value>
<Image Source="cancel.png" />
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
</ToggleButton>
Run Code Online (Sandbox Code Playgroud)
有什么不同?为什么两者都不起作用?我不喜欢为某些东西创建一个"资源",因为它将我的代码分开并且可能使它更难以阅读.
是的,我知道我的例子可以像这样简化
<ToggleButton>
<Image Source="cancel.png" />
</ToggleButton>
Run Code Online (Sandbox Code Playgroud)
但那不是重点.