[英]Databinding WPF
我想用TextBox創建一個控件,並將TextBox.Text屬性與我自己的Dependency Property 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));
}
看來您忘記設置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>
我是從頭開始寫的,希望這里不要打錯字。
希望能幫助到你,
干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.