gpt4 book ai didi

c# - 按钮的依赖属性

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:39 24 4
gpt4 key购买 nike

我正在尝试为按钮创建一个名为“IsVisibleWhenReadOnly”的 bool 属性。我希望将它用在 StackPanel 中的按钮上,这样它们是否可见取决于数据是否处于 ReadOnly 状态。即当处于ReadOnly 状态时,Save 和Cancel 按钮是Hidden,但是Edit 按钮是Visible。单击“编辑”按钮时,ReadOnly 状态变为 false,“取消”和“保存”按钮变为可见,而“编辑”按钮隐藏。

我的属性(property)代码:

public bool IsVisibleWhenReadOnly
{
get { return (bool)GetValue(IsVisibleWhenReadOnlyProperty); }
set { SetValue(IsVisibleWhenReadOnlyProperty, value); }
}

// Using a DependencyProperty as the backing store for IsVisibleWhenReadOnly.
public static readonly DependencyProperty IsVisibleWhenReadOnlyProperty =
DependencyProperty.Register("IsVisibleWhenReadOnly",
typeof(bool),
typeof(Button),
new PropertyMetadata(true));

按钮样式:

<Style TargetType="{x:Type Button}">
<Setter Property="Visibility">
<Setter.Value>
<Binding Path="IsVisibleWhenReadOnly" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Mode="OneWay">
<Binding.Converter>
<utils:BoolToVisibilityConverter/>
</Binding.Converter>
</Binding>
</Setter.Value>
</Setter>
</Style>

和按钮代码:

<Button Name="btnEdit" Content="Edit" MinWidth="75" Height="25" 
Click="btnEdit_Click" IsVisibleWhenReadOnly="true" />

IsReadOnly 是另一个运行良好的依赖属性,并根据其值启用/禁用控件,但我希望它影响可见性,而不是启用。

不幸的是,我在编译时遇到三个错误:

The member "IsVisibleWhenReadOnly" is not recognized or is not accessible.
The property 'IsVisibleWhenReadOnly' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'.
The property 'IsVisibleWhenReadOnly' was not found in type 'Button'.

我猜它在 typeOf(Button), 行中,但将其更改为 'BaseWindow'(这是我的 ' 的 typeOf() 值IsReadOnly' 属性)没有任何区别。我也很确定我的 BoolToVisibilityConverter 不是问题所在。

谁能看出我做错了什么并指出正确的方向?

编辑:如果可能的话,我想将依赖属性与不仅仅是按钮一起使用。例如,StackPanels、CheckBoxes 等,因此不限于按钮的解决方案是理想的。

最佳答案

你应该使用 attached dependency property如果您想搭载现有控件。所以像这样:

public static void SetIsVisibleWhenReadOnly(UIElement element, bool value)
{
element.SetValue(IsVisibleWhenReadOnlyProperty, value);
}
public static bool GetIsVisibleWhenReadOnly(UIElement element)
{
return (bool)element.GetValue(IsVisibleWhenReadOnlyProperty);
}
// Using a Registerd DependencyProperty as the backing store for IsVisibleWhenReadOnly.
public static readonly DependencyProperty IsVisibleWhenReadOnlyProperty =
DependencyProperty.RegisterAttached("IsVisibleWhenReadOnly",
typeof(bool),
typeof(Button),
new PropertyMetadata(true));

我还会考虑对可见性转换器进行多重绑定(bind),这样您就可以在确定要返回的可见性值时访问 IsReadOnly 和 IsVisibileWhenReadOnly。

关于c# - 按钮的依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15632428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com