當開發WPF UserControls時,將子控件的DependencyProperty公開爲UserControl的DependencyProperty的最佳方式是什麼?以下示例顯示了當前如何將TextBox內的Text屬性公開在UserControl中。當然,有一個更好/更簡單的方法來實現這一目標?公開DependencyProperty
<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(); }
}
}
這種方式最適合在Silverlight 4中不存在 'FindAncestor' – 2010-09-03 04:11:44
這爲我工作,但它看起來像你可以不使用相同的`x:Class`和`x:Name`。我必須有一個像`WpfApplication1.SliderLabel`這樣的類,並且給了它一個像SliderLabelControl這樣的名字。否則它會抱怨這個名字已經存在。 – 2016-03-13 22:42:01