在开发WPF UserControls时,将子控件的DependencyProperty作为UserControl的DependencyProperty公开的最佳方法是什么?以下示例显示了我目前如何公开UserControl内部TextBox的Text属性。肯定有更好/更简单的方法来实现这一点吧?
<UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Background="LightCyan">
<TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</StackPanel>
</UserControl>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication3
{
public partial class UserControl1 : UserControl
{
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
public string Text
{
get { return GetValue(TextProperty) as string; }
set { SetValue(TextProperty, value); }
}
public UserControl1() { InitializeComponent(); }
}
}
x:Class
和x:Name
。我必须有一个类似于WpfApplication1.SliderLabel
的类,并将其命名为SliderLabelControl
。否则它会抱怨名称已经存在。 - Adam Plocher