Expose DependencyProperty

前端 未结 2 679
遇见更好的自我
遇见更好的自我 2020-12-13 05:20

When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example s

相关标签:
2条回答
  • 2020-12-13 05:38

    That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name.

    <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>
    

    Sometimes we've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.

    0 讨论(0)
  • 2020-12-13 05:43

    You can set DataContext to this in UserControl's constructor, then just bind by only path.

    CS:

    DataContext = this;
    

    XAML:

    <TextBox Margin="8" Text="{Binding Text} />
    
    0 讨论(0)
提交回复
热议问题