C# 数据绑定WPF

C# 数据绑定WPF,c#,wpf,data-binding,C#,Wpf,Data Binding,我想创建一个带有文本框的控件,并将TextBox.Text属性与我自己的依赖属性TextProp绑定。(某种实验)然而,绑定不起作用!我做错了什么 XAML: 看起来您忘记设置了,绑定可以从中获得实际属性 请尝试以下操作之一: C# 或 <UserControl x:Class="WpfApplication1.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/x

我想创建一个带有文本框的控件,并将TextBox.Text属性与我自己的依赖属性TextProp绑定。(某种实验)然而,绑定不起作用!我做错了什么

XAML:


看起来您忘记设置了,绑定可以从中获得实际属性

请尝试以下操作之一:

C#

<UserControl x:Class="WpfApplication1.UserControl1"
             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:WpfApplication1"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
            <TextBox Text="{Binding TextProp}" x:Name="textb"/>
    </UserControl>

或2

<UserControl x:Class="WpfApplication1.UserControl1"
             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:WpfApplication1">
        <TextBox DataContext="{Binding RelativeSource={RelativeSource FindAncestory, AncestorType={x:Type local:UserControl}}} Text="{Binding TextProp}" x:Name="textb"/>
</UserControl>

public UserControl1()
{
   InitializeComponent();
   TextProp = "fwef";
   DataContext = this;
}
<UserControl x:Class="WpfApplication1.UserControl1"
             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:WpfApplication1"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
            <TextBox Text="{Binding TextProp}" x:Name="textb"/>
    </UserControl>
<UserControl x:Class="WpfApplication1.UserControl1"
             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:WpfApplication1">
        <TextBox DataContext="{Binding RelativeSource={RelativeSource FindAncestory, AncestorType={x:Type local:UserControl}}} Text="{Binding TextProp}" x:Name="textb"/>
</UserControl>