C# 将 XAML 中的可见性绑定到可见性属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/384776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding Visibility in XAML to a Visibility property
提问by Jared
I've seen on the internet quite a few examples of binding a boolean to the Visibility property of a control in XAML. Most of the good examples use a BooleanToVisibiliy converter.
我在 Internet 上看到了很多将布尔值绑定到 XAML 中控件的 Visibility 属性的示例。大多数优秀示例都使用 BooleanToVisibiliy 转换器。
I'd like to just set the Visible property on the control to bind to a System.Windows.Visibility property in the code-behind, but it doesn't seem to want to work.
我只想将控件上的 Visible 属性设置为绑定到代码隐藏中的 System.Windows.Visibility 属性,但它似乎不想工作。
This is my XAML:
这是我的 XAML:
<Grid x:Name="actions" Visibility="{Binding Path=ActionsVisible, UpdateSourceTrigger=PropertyChanged}" />
This is the code for the property:
这是该属性的代码:
private Visibility _actionsVisible;
public Visibility ActionsVisible
{
get
{
return _actionsVisible;
}
set
{
_actionsVisible = value;
}
}
In the constructor of the Window, I also have this call:
在 Window 的构造函数中,我也有这个调用:
base.DataContext = this;
When I update either ActionsVisible or this.actions.Visibility, the state doesn't transfer. Any ideas to what might be going wrong?
当我更新 ActionsVisible 或 this.actions.Visibility 时,状态不会转移。对可能出什么问题的任何想法?
采纳答案by Craig Shearer
I think the problem is that WPF can't know that your ActionsVisible property has changed since you've not notified the fact.
我认为问题在于 WPF 无法知道您的 ActionsVisible 属性已更改,因为您没有通知事实。
Your class will need to implement INotifyPropertyChanged, then in your set method for ActionsVisible you'll need to fire the PropertyChanged event with ActionsVisible as the property name that has changed.
您的类将需要实现 INotifyPropertyChanged,然后在 ActionsVisible 的 set 方法中,您需要使用 ActionsVisible 作为已更改的属性名称来触发 PropertyChanged 事件。
Hope this helps...
希望这可以帮助...
回答by NR.
Change your property to be a DependencyProperty. This will handle the updating for you.
将您的属性更改为 DependencyProperty。这将为您处理更新。
public Visibility ActionsVisible
{
get { return (Visibility)GetValue(ActionsVisibleProperty); }
set { SetValue(ActionsVisibleProperty, value); }
}
// Using a DependencyProperty as the backing store for ActionsVisible. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ActionsVisibleProperty =
DependencyProperty.Register("ActionsVisible", typeof(Visibility), typeof(FooForm));
回答by bedi
Write: NotifyPropertyChanged("ActionsVisible")
写: NotifyPropertyChanged("ActionsVisible")