1
我有一个只有一个文本块的用户控件。我有自定义依赖项属性来设置文本块的文本。不过,我在绑定工作方面遇到了一些问题。绑定到usercontrol依赖属性不起作用
这里的用户控件:
<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();
}
}
正如评论说,设置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的绑定不?
由于“Self”是TextBlock,所以不起作用,但无论如何要感谢。 {Binding ElementName = UserControlName,Path = TestProperty}在我从usercontrol中删除datacontext行后工作。 – FINDarkside
它当然应该是'RelativeSource = {RelativeSource AncestorType = UserControl}'。作为一般规则,*从不*设置UserControl的DataContext到自身,因为这将有效地防止从UserControl的Parent继承“外部”DataContext。 – Clemens
你是对的,我犯了一个错误。它指出你不能设置你的UserControl的DataContext。 –