LoginSignup
4
5

More than 5 years have passed since last update.

WPF UIのプロパティをグローバル変数として扱う

Posted at

小ネタ。

お前のMVVMのやり方がおかしいと言われそうな話だけど、UIのプロパティを、グローバル変数のように、どこのクラスからでもアクセスしたいと思ったので、それ用のやり方を作った。
Staticおじさんである。

こういうクラスを作り、

filename
    public class GenericBinding<T> : GalaSoft.MvvmLight.ViewModelBase
    {
        public GenericBinding(FrameworkElement ui, DependencyProperty dp)
        {
            this.Value = (T)ui.GetValue(dp);
            AddBinding(ui, dp);
        }

        public GenericBinding<T> AddBinding(FrameworkElement ui, DependencyProperty dp)
        {
            var binding = new Binding();
            binding.Source = this;
            binding.Mode = BindingMode.TwoWay;
            binding.Path = new PropertyPath("Value");           
            ui.SetBinding(dp, binding);
            return this;
        }

        public Action<T> ChangeValueAction { get; set; }

        T _value;
        public T Value
        {
            get
            {
                return _value;
            }
            set
            {
                if (_value.Equals(value)==false)
                {
                    _value = value;
                    RaisePropertyChanged("Value");
                    if (ChangeValueAction != null) ChangeValueAction(_value);
                }
            }
        }
    }

こういう感じの静的クラスを作り、

filename
    public static class State
    {
        public static GenericBinding<double> MaxImageViewNum { get; set; }
        public static GenericBinding<string> NameText { get; set; }
    }

WPFのコードビハインドで、登録を行います。
XAML上で、UIオブジェクトには名前をつけて、DependencyPropertyは適切なものをつけてください。

filename

    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();      

            State.MaxImageViewNum = new GenericBinding<double>(numericUpDown1, NumericUpDown.ValueProperty);
            State.NameText = new GenericBinding<string>(textBlock1, TextBlock.TextProperty);
        }
     }

使い方は、State.MaxImageViewNum.Valueという感じで、どこからでも呼び出せ、値の更新もUIに反映されます。
乱用するとおかしなことになるのでしょうが、複数のオブジェクトで使う設定などには便利だと思います。
案外、今のソースでは書き換え可能になっていますが、ReadOnly版の方が便利かもしれません。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5