基於WPF系統框架設計(9)-多值綁定之IMultiValueConverter

應用場景

我想把View層的一個佈局控件和功能按鈕傳到ViewModel層,達到動態變動佈局,同時靈活獲取功能按鈕的屬性,讓View和ViewModel徹底分離,而不受View層影響。數組

最後我想到使用IMultiValueConverter實現多參傳入ViewModel層來解決,不知道還有沒有更好的辦法?佈局

基本原理:要將值轉換器與 MultiBinding 關聯,請建立一個實現 IMultiValueConverter 接口的類,而後實現 Convert 和 ConvertBack 方法。
集合中的各個綁定能夠具備本身的值轉換器。this

使用 MultiBinding,您能夠將綁定目標屬性綁定到源屬性列表,而後應用邏輯以使用給定的輸入生成值。spa

實現步驟

    添加繼承IMultiValueConverter接口的類並實現接口 code

    注意:返回的values必定要轉爲數組列表values.ToArray()對象

參考以下代碼

using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace TLAgent.SecurityManager.WPF.MultiBindings
{
  public class DataConverter : IMultiValueConverter
  {
    #region IMultiValueConverter Members

    public object Convert(object[] values, Type targetType,
      object parameter, System.Globalization.CultureInfo culture)
    {
        return values.ToArray() ;
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
      object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
  }
}

在XAML中進行多參綁定

<Fluent:Button Header="添加用戶" Icon="Images\Green.png" LargeIcon="Images\GreenLarge.png" x:Name="BtnAddUser" Command="{Binding AddUserCommand}">
                        <Fluent:Button.CommandParameter>
                            <MultiBinding Converter="{ StaticResource ResourceKey=dataConverter}" Mode="TwoWay">
                                <MultiBinding.Bindings>
                                    <Binding ElementName="BtnAddUser"/>
                                    <Binding ElementName="dockManager "/>
                                </MultiBinding.Bindings>
                            </MultiBinding>
                        </Fluent:Button.CommandParameter>
                        
                    </Fluent:Button>
<Window.Resources>
        <local:DataConverter x:Key="dataConverter"/>
</Window.Resources>

ViewModel中進行命令和方法綁定

注意:DelegateCommand<object[]>的參數是要支持對象數組。blog

using System;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;
using Xceed.Wpf.AvalonDock;
using Xceed.Wpf.AvalonDock.Layout;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
using UserControl = System.Windows.Controls.UserControl;

namespace TLAgent.SecurityManager.WPF.ViewModels
{
    public class MainWindowViewModel : NotificationObject
    {
        public ICommand ExitSystemCommand { get; set; }

        public ICommand AddUserCommand { get; set; }

        public ICommand OpenHelpCommand { get; set; }

        public MainWindowViewModel()
        {
            ExitSystemCommand = new DelegateCommand(this.OnExit);
            OpenHelpCommand = new DelegateCommand(this.OnOpenSupport);
            AddUserCommand = new DelegateCommand<object[]>(this.AddUser);
        }


        private void CreateTab(DockingManager dockManager, string tabName, UserControl control)
        {
            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();
            if (firstDocumentPane != null)
            {
                LayoutDocument doc2 = new LayoutDocument();
                doc2.Title = tabName;
                doc2.Content = control;
                doc2.IsActive = true;
                firstDocumentPane.Children.Add(doc2);
            }
        }

        private void OnExit()
        {
            MessageBoxResult result = MessageBox.Show("肯定要退出系統嗎?", "確認消息", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (result == MessageBoxResult.OK)
            {
                Application.Current.Shutdown();
            }
        }

        private void OnOpenSupport()
        {
            MessageBox.Show("幫助窗口!");
        }
        
       private void AddUser(object[] objParam)
       {
            if (objParam.Length == 2)
            {
                Fluent.Button button = (Fluent.Button)objParam[0];
                DockingManager dockingManager = (DockingManager)objParam[1];
                UserControl control;
                control = new UserControl1();

                CreateTab(dockingManager, button.Header.ToString(), control);
            }
      }
    }
}

控件綁定

這樣就能夠在方法AddUer的參數中取得View層綁定的兩個控件:繼承

<MultiBinding.Bindings>
     <Binding ElementName="BtnAddUser"/>
     <Binding ElementName="dockManager "/>
</MultiBinding.Bindings>

這樣基本就實現了從View層傳多個對象到ViewModel層了。眨眼接口

相關文章
相關標籤/搜索