Pregunta

Al desarrollar controles de usuario de WPF, ¿cuál es la mejor manera de exponer una propiedad de dependencia de un control secundario como una propiedad de dependencia del control de usuario?El siguiente ejemplo muestra cómo expondría actualmente la propiedad Text de un TextBox dentro de un UserControl.Seguramente hay una manera mejor y más sencilla de lograr esto.

<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(); }
    }
}
¿Fue útil?

Solución

Así es como lo estamos haciendo en nuestro equipo, sin la búsqueda de RelativeSource, sino nombrando el UserControl y haciendo referencia a las propiedades por el nombre del UserControl.

<UserControl x:Class="WpfApplication3.UserControl1" x:Name="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 Path=Text, ElementName=UserControl1}" />
    </StackPanel>
</UserControl>

Sin embargo, a veces nos hemos encontrado haciendo demasiadas cosas de UserControl y muchas veces hemos reducido nuestro uso.También seguiría la tradición de nombrar cosas como ese cuadro de texto como PART_TextDisplay o algo así, para que en el futuro puedas crear una plantilla y mantener el mismo código subyacente.

Otros consejos

Puede configurar DataContext en esto en el constructor de UserControl y luego vincularlo solo por ruta.

CS:

DataContext = this;

XAML:

<TextBox Margin="8" Text="{Binding Text} />
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top