我想用TextBox创建一个控件,并将 TextBox.Text 属性与我自己的依赖属性 TextProp 绑定在一起。 (某种实验)然而,绑定不起作用!我做错了什么?
XAML:
<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 Text="{Binding TextProp}" x:Name="textb"/>
</UserControl>
C#:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
TextProp = "fwef";
}
public string TextProp
{
get { return ( string )GetValue(TextPropProperty); }
set { SetValue(TextPropProperty, value); }
}
public static readonly DependencyProperty TextPropProperty =
DependencyProperty.Register("TextProp",typeof( string ),typeof(UserControl1));
}
答案 0 :(得分:2)
看起来你忘了设置DataContext,从Binding可以获得实际属性...
请尝试以下方法之一:
<强> C#强>
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>
或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>
我是从头开始写的,希望我没有在这里写错字。
希望它有所帮助,
干杯。