Databinding WPF
I wanted to create a control with a TextBox and to bind TextBox.Text property with my own Dependency Property TextProp. (Some kind of experiment) However, the binding does not work! What I am doing wrong?
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));
}
It looks like you forgot to set DataContext, from where Binding could get actual property...
Try one of the following:
C#
public UserControl1()
{
InitializeComponent();
TextProp = "fwef";
DataContext = this;
}
Or
<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>
Or 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>
I wrote this from head, hope I didn't make any typo here.
Hope it helps,
Cheers.
精彩评论