如何在WPF中公开子控件属性?

问题描述 投票:0回答:1

我编写了一个用户控件

MyCustomToggleButton
,其中封装了一个切换按钮。我想根据切换按钮的
IsChecked
属性显示或隐藏网格。我添加了一个依赖属性
Expanded
(我不介意再次重用
IsChecked
属性),我通过切换按钮的
Checked
事件进行控制。

<controls:CustomToggleButton x:Name="MyCustomToggleButton">

<Grid Visibility="{Binding Expanded, ElementName=MyCustomToggleButton, Converter={StaticResource BooleanToVisibilityConverter}, FallbackValue=False}"
public static readonly DependencyProperty ExpandedProperty =
    DependencyProperty.Register(nameof(Expanded), typeof(bool), typeof(CustomToggleButton), new PropertyMetadata(false));


public bool Expanded
{
    get
    {
        return (bool)GetValue(ExpandedProperty);
    }
    set
    {
        SetValue(ExpandedProperty, value);
    }
}

public MyCustomToggleButton()
{
    InitializeComponent();
     
    // ToggleButton is the name of the toggle button defined in XAML.
    ToggleButton.Checked += (sender, e) =>
    {
        Expanded = true;
    };
    ToggleButton.Unchecked += (sender, e) =>
    {
        Expanded = false;
    };
}

如何将用户控件的

Expanded
属性绑定到切换按钮的
IChecked
属性?

wpf binding user-controls
1个回答
0
投票

“如何将用户控件的 Expanded 属性绑定到切换按钮的 IChecked 属性?”

<UserControl>
  <ToggleButton IsChecked="{Binding RelativeSource="{RelativeSource AncestorType=UserControl}, Path=Expanded}" />
</UserControl>

创建一个名为

CustomToggleButton
的类意味着您想要扩展默认
ToggleButton
的行为。在这种情况下,您应该字面意义上的 extend
ToggleButton
而不是包裹它:

class CustomToggleButton : ToggleButton
{
  // Optional: Override the default Style if desired
  static CustomToggleButton()
    => DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomToggleButton), new FrameworkPropertyMetadata(typeof(CustomToggleButton)));
}

然后将新的默认样式添加到 Generic.xaml,您可以在其中自定义布局(如果需要)

<Style TargetType="CustomToggleButton">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="CustomToggleButton">

        ...
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
© www.soinside.com 2019 - 2024. All rights reserved.