我正在尝试创建一个具有少量DependencyProperties
的用户控件,这些控件在用户控件中转发给子控件。经过几次尝试,我得到了这个工作。为了测试一个小例子。
在示例中,我有一个名为Ctrl
的用户控件,它只包含TextBox
并公开Text
的{{1}}属性。此控件用于包含TextBox
和我的自定义TextBox
的窗口,这些窗口绑定到同一属性。
XAML
Ctrl
背后的代码
<UserControl x:Class="trying.Ctrl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource self}}"
Height="Auto" Width="Auto">
<TextBox Text="{Binding MyText}" />
</UserControl>
XAML
using System.Windows;
using System.Windows.Controls;
namespace trying
{
public partial class Ctrl : UserControl
{
public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register(
"MyText",
typeof( string ),
typeof( UserControl ),
new FrameworkPropertyMetadata( default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string MyText
{
get { return (string)GetValue( MyTextProperty ); }
set { SetValue( MyTextProperty, value ); }
}
public Ctrl()
{
InitializeComponent();
}
}
}
背后的代码
<Window x:Class="trying.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cc="clr-namespace:trying"
DataContext="{Binding RelativeSource={RelativeSource self}}"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding DisplayText}" />
<cc:Ctrl Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" MyText="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DisplayText}" />
</Grid>
</Window>
我如何发布它的工作代码。我现在的问题是:我做错了什么,我必须使用绑定
using System.Windows;
using System.ComponentModel;
namespace trying
{
public partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
private string m_displayText = "asdf";
public string DisplayText
{
get { return m_displayText; }
set
{
m_displayText = value;
NotifyPropertyChanged( "DisplayText" );
}
}
public Window1()
{
InitializeComponent();
}
}
}
绑定 MyText="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}
的{{1}}属性时,不能像绑定原始MyText
时使用的那样简单绑定吗?
如果我不以这种方式绑定它将无效,我收到警告
Ctrl
与原始TextBox
?
。
答案 0 :(得分:2)
UserControl
的{{1}}指向自身,因此对控件实例的任何绑定都将查看DataContext
实例,而不是继承的Ctrl
尝试在树下进一步设置DataContext
:
DataContext