繁体   English   中英

从CodeBehind将可见性绑定到Viewmodel的属性[从View到ViewModel]

[英]Binding Visibility to Viewmodel's property [ from View To ViewModel] from CodeBehind

我正在DockManager上动态创建绑定,以便在ViewModel中具有一个告诉我View / ViewModel是否可见的属性。

我已经完成了其他绑定的测试,但在这种情况下,我需要将视图绑定到ViewModel而不是相反

我的代码看起来像

VisibilityToBooleanConverter converter = new VisibilityToBooleanConverter();

var myBinding = new Binding
{
    Source = pane.Content, //this is the view
    Path = new PropertyPath("Visibility"),
    Mode = BindingMode.OneWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
    Converter = converter
};

BindingOperations.SetBinding(pane.DataContext,) //<-- how do I tell that I've to bind to a ViewModel?

//BindingOperations.SetBinding((UIElement)pane.Content, UIElement.VisibilityProperty, myBinding); //this was the test I've done but with no luck

有什么建议吗?

更新#1

正如我所建议的,我试图更好地解释我的情况。

我有一个显示不同视图的DockManager。 这些视图中的一些具有实时更新,而实时更新的频率很高。 如果它们不可见,则对其进行更新是没有用的。

因此,首先,我尝试绑定IsVisible,但正如您所告诉的那样,这是不可能的(无设置方法)。

我的问题是可以在后面的代码中绑定Visibility属性,以便我可以某种方式将这些信息保存在viewmodel中

绑定需要一个DependencyProperty。 我将尝试在OneWayToSource模式下使用Binding并使用常见的BooleanToVisibilityConverter转换器绑定Visibility属性。

var converter = new BooleanToVisibilityConverter();

var myBinding = new Binding
{
    Path = new PropertyPath("IsVisiblePropertyInViewModel"),
    Mode = BindingMode.OneWayToSource,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
    Converter = converter
};

BindingOperations.SetBinding(pane, UIElement.Visibility, binding);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM