1.Control1有个TextBlock和自定义依赖属性
xaml:
UserControl x:Class="TestStyleTrigger.Control1"
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:local="clr-namespace:TestStyleTrigger"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<TextBlock Text="{Binding Str}"/>
</Grid>
</UserControl>
C#:
public partial class Control1 : UserControl
{
public Control1()
{
InitializeComponent();
this.DataContext = this;
}
public string Str
{
get { return (string)GetValue(StrProperty); }
set { SetValue(StrProperty, value); }
}
// Using a DependencyProperty as the backing store for Str. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StrProperty =
DependencyProperty.Register("Str", typeof(string), typeof(Control1), new PropertyMetadata("str"));
}
2.主界面上调用Control1:
xaml:
<Window x:Class="TestStyleTrigger.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:TestStyleTrigger"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:Control1 Str="{Binding StrText}" Width="100" Height="100" />
</Grid>
</Window>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
StrText = "strtext";
}
public string StrText { get; set; }
}
运行结果:
绑定错误:
3.解决办法:
不能为UserControl 设置 DataContext
而应该为 FrameworkElement设置DataContext
将Control1中的 this.DataContext = this; 改为
(this.Content as FrameworkElement).DataContext = this;
最后正确显示结果: