У меня есть usercontrol, в котором есть только один текстовый блок. У меня есть свойство пользовательской зависимости, чтобы установить текст текстового блока. Однако у меня есть некоторые проблемы при получении обязательной работы.Привязка к usercontrol dependencyproperty не работает
Вот 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();
}
}
MainWindow:
<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 = "СравниваемаяСтрока" работает, но если я пытаюсь сделать привязку это не будет работать даже если одно и то же обязательство работает для 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')
Установка имени для MainWindow и затем связывание, как это:
<local:TestControl TestProperty="{Binding ElementName=MainWindowName, Path=TestValue}"/>
Работает, но зачем мне ElementName, когда обязательными для TextBlock не?
Не работает, так как «Я» - это TextBlock, но в любом случае спасибо. {Binding ElementName = UserControlName, Path = TestProperty} работал после того, как я удалил строку datacontext из usercontrol. – FINDarkside
Нужно, конечно, «RelativeSource = {RelativeSource AncestorType = UserControl}». Как правило, * никогда не устанавливайте DataContext UserControl для себя, так как это эффективно предотвратит наследование «внешнего» DataContext из родителя UserControl. – Clemens
Вы оба правы, я допустил ошибку. То, что вы не можете установить DataContext своего UserControl. –