我试图为按钮创建一个布尔属性,名为'IsVisibleWhenReadOnly
'。我希望这可以在StackPanel中的按钮上使用,因此它们可以显示或不显示,具体取决于数据是否处于ReadOnly
状态。即当在ReadOnly
状态下,保存和取消按钮是隐藏的,但编辑按钮是可见的。当单击编辑按钮时,ReadOnly
状态变为false,并且取消和保存按钮变为可见,并且编辑按钮被隐藏。按钮的依赖项属性
我的属性代码:
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不是问题。
任何人都可以看到我做错了什么,并指出我在正确的方向吗?
编辑:如果可能的话,我想使用不仅仅是按钮的依赖属性。例如,StackPanels,CheckBoxes等,所以不仅限于Buttons的解决方案是理想的。
你在哪里实现了'DependencyProperty'?你扩展了Button类吗? – DHN 2013-03-26 08:43:01
DP是在我所有的Windows继承的BaseWindow.cs中实现的。我没有扩展Button - 在阅读DP时我没有看到这条指令。 – mcalex 2013-03-26 08:54:56
那么你必须使用'AttachedProperty',因为答案已经说明了。 – DHN 2013-03-26 10:18:20