【发布时间】:2013-03-26 08:27:30
【问题描述】:
我正在尝试为按钮创建一个名为“IsVisibleWhenReadOnly”的布尔属性。我希望将其用于 StackPanel 中的按钮,因此它们是否可见取决于数据是否处于 ReadOnly 状态。即当处于ReadOnly 状态时,保存和取消按钮是隐藏的,但编辑按钮是可见的。当点击 Edit 按钮时,ReadOnly 状态变为 false,Cancel 和 Save 按钮变为可见,而 Edit 按钮被隐藏。
我的房产代码:
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”(这是我的“IsReadOnly”属性的typeOf() 值)并没有什么不同。我也很确定我的 BoolToVisibilityConverter 不是问题。
谁能看到我做错了什么并指出我正确的方向?
编辑:如果可能的话,我想将 Dependency 属性与不仅仅是按钮一起使用。例如,StackPanels、CheckBoxes 等,因此不限于按钮的解决方案是理想的。
【问题讨论】:
-
你在哪里实现了
DependencyProperty?您是否扩展了Button类? -
DP 在我所有的 Windows 继承的 BaseWindow.cs 中实现。我没有扩展 Button - 在 DP 上阅读时我没有看到此说明。
-
那么你必须使用
AttachedProperty,因为答案已经说明了。
标签: c# wpf dependency-properties