Lors du développement de UserControls WPF, quel est le meilleur moyen d'exposer un DependencyProperty d'un contrôle enfant en tant que DependencyProperty du UserControl? L'exemple suivant montre comment j'exposer actuellement la propriété Text d'un TextBox dans un UserControl. Sûrement il y a une manière meilleure/plus simple d'accomplir ceci?Expose 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(); }
}
}
cette façon fonctionne le mieux dans Silverlight 4, où il n'y a pas 'FindAncestor' –
Cela a fonctionné pour moi, mais il ne semble pas que vous pouvez utilise les mêmes 'x: Class' et' x: Name'. Je devais avoir une classe comme 'WpfApplication1.SliderLabel' et je lui ai donné un nom comme' SliderLabelControl'. Sinon, il s'est plaint que le nom existait déjà. –