我有一个Control
,可见性被绑定到一个视图模型,但也允许用户直接关闭控件。理想情况下,我希望CloseDialog
函数检查Visibility
上的绑定,如果存在,则直接更新绑定值(也就是ViewModel的绑定值)而不是覆盖它但是我是如何实际更新价值本身
public void CloseDialog()
{
Control visibileObject = this;
//Check to ensure we have no binding set, if we do then update the binding expression
Binding myBinding;
#if (!SILVERLIGHT)
myBinding = BindingOperations.GetBinding(visibileObject, Control.VisibilityProperty);
#else
BindingExpression bindingExpression = visibileObject.GetBindingExpression(Control.VisibilityProperty);
myBinding = bindingExpression.ParentBinding;
#endif
if (myBinding != null)
{
//Here update binding target to be Visibility.Collapsed
}
}
答案 0 :(得分:0)
您可以使用BindingExpression的UpdateSource方法更新源代码。
bindingExpression.UpdateSource();
它将使用VisibilityProperty的当前值更新您的ViewModel属性。
但您也可以在CloseDialog方法中设置控件的Visibility。如果存在(双向)绑定,它将自动更新您的属性。
public void CloseDialog()
{
this.Visibility = Visibility.Collapsed;
}
答案 1 :(得分:0)
我可能会误解你,但我建议直接使用转换器将可见性绑定到视图模型,以将视图模型的值转换为Visibility值。如果绑定是TwoWay,则可以更新模型,反之亦然。这可以在您的XAML代码中完成:
Visibility="{Binding Path=DataContext.Value,
ElementName=MyDataProperty,
Mode=TwoWay,
Converter={StaticResource ValueToVisibiltyConverter}}"
并且转换器会在转换中执行类似的操作:
public override object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
if (value == null)
{
return Visibility.Visible;
}
if (value.Equals("HideMe")
{
return Visibility.Collapsed;
}
return Visibility.Visible;
}
public override object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
// TODO! Convert back to view model value
}