【发布时间】:2016-02-14 17:12:36
【问题描述】:
我有一个用户控件,里面只有一个文本块。我有自定义依赖属性来设置文本块的文本。但是,我在绑定工作时遇到了一些问题。
这是用户控件:
<UserControl x:Class="TestWpf2.TestControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding TestProperty}"></TextBlock>
</UserControl>
public partial class TestControl : UserControl
{
public static readonly DependencyProperty TestPropertyTestDependencyProperty = DependencyProperty.Register("TestProperty", typeof(string), typeof(TestControl));
public string TestProperty
{
get { return (string)GetValue(TestPropertyTestDependencyProperty); }
set { SetValue(TestPropertyTestDependencyProperty, value); }
}
public TestControl()
{
InitializeComponent();
}
}
主窗口:
<Window x:Class="TestWpf2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpf2"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel>
<local:TestControl TestProperty="TestString"/> <!-- Works -->
<local:TestControl TestProperty="{Binding TestValue}"/><!-- Does not work -->
<TextBlock Text="{Binding TestValue}"/> <!-- Works -->
</StackPanel>
</Window>
public partial class MainWindow : Window
{
public string TestValue { get; set; }
public MainWindow()
{
TestValue = "TestString";
InitializeComponent();
}
}
正如 cmets 所说,设置 TestProperty="TestString" 有效,但如果我尝试进行绑定,即使相同的绑定适用于 TextBlock,它也将不起作用。
这是绑定错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'TestValue' property not found on 'object' ''TestControl' (Name='')'. BindingExpression:Path=TestValue; DataItem='TestControl' (Name=''); target element is 'TestControl' (Name=''); target property is 'TestProperty' (type 'String')
将名称设置为主窗口,然后像这样绑定:
<local:TestControl TestProperty="{Binding ElementName=MainWindowName, Path=TestValue}"/>
有效,但为什么我需要 ElementName,而 TextBlock 的绑定不需要?
【问题讨论】:
标签: c# wpf xaml data-binding