【问题标题】:Is there any way to bind a variable to another variable? (WPF Project)有没有办法将一个变量绑定到另一个变量? (WPF 项目)
【发布时间】:2019-06-24 03:32:13
【问题描述】:

我已经为 Views 中的一个类中的一个变量设置了边框可见性绑定,称为 P,其中 P 是布尔类型。我在 ViewModels 的一个类中有另一个变量,称为 M,其中 M 是字典,枚举由三个元素组成,例如 A、B 和 C。我如何将 P 绑定到 M.value,如果 P 为假, M.value 设置为 A,如果 P 为真,则 M.value 设置为 B 或 C(取决于某些条件),这样边框在 M.value 为 B 或 C 时可见,而在 M 时不可见.value 是 A?

到目前为止,我已经实现了将边框可见性绑定到 P 并且它可以工作(当 P 为真时,它是可见的,当 P 为假时,它不可见)。

enum E {
        A,B,C
}

public class ClassInViews {
    private bool picked = false;
    public bool Picked {get; set;}
}

public class ClassInViewModels {

    private Dictionary<(...An arbitrary class in Models),E> M;
}

【问题讨论】:

  • 有人可以帮忙吗?

标签: c# wpf variables binding


【解决方案1】:

由于您想将其绑定到字典的更改,因此我将使用ObservableDictionary 并通过引发“Picked”属性的更改事件来响应集合中的任何更改。所以你的 ViewModel 必须实现 INotifyPropertyChanged。

那么最简单的事情就是将你的逻辑写到 P 的 getter 中。

public bool Picked 
{
  get
  {
    /*Your logic here*/
  }
}

第二个选项:您可以创建一个 IValueConverter 将您的给定目录转换为可见性。

public class Bool2VisibilityConverter : MarkupExtension, IValueConverter
    {
        static Bool2VisibilityConverter _converter;

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_converter == null)
            {
                _converter = new Bool2VisibilityConverter();
            }
            return _converter;
        }

        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var dic = value as ObservableDictionaray<YourTypesHere>;

            if (dic == null)
              return Visibility.Collapsed;


            bool visible = /* Check the Dictionary with your logic */;

            return (bool) visible ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementexException();
        }
        #endregion
    }

然后你可以简单地用它来转换字典:

<Button Visibility="{Binding Dictioanry, Converter={conv:Bool2VisibilityConverter}}" />

【讨论】:

  • 很高兴 +1 理解它。
猜你喜欢
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
相关资源
最近更新 更多