WPF MVVM RadioButton Binding

  • 7853
  • 0
  • 2013-07-26

摘要:WPF RadioButton Binding

找了半天,終於找到看的懂的範例,消化吸收後,另寫一個範例來記錄一下。

我先放了三個 RadioButton 在畫面上:


<Window x:Class="RadioButtonBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ViewModel;assembly=ViewModel"        
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModelClass/>
    </Window.DataContext>
    <Window.Resources>
        <local:MyConverter x:Key="MyConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel Width="156" Orientation="Horizontal">
            <RadioButton GroupName="name" IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, Converter={StaticResource MyConverter}, ConverterParameter=0}" Content="Option A" Width="45"/>
            <RadioButton GroupName="name" IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, Converter={StaticResource MyConverter}, ConverterParameter=1}" Content="Option B" Width="45"/>
            <RadioButton GroupName="name" IsChecked="{Binding Path=CurrentOption, Mode=TwoWay, Converter={StaticResource MyConverter}, ConverterParameter=2}" Content="Option C" Width="60"/>

        </StackPanel>
        <Button Content="Show your selection" Command="{Binding Path=CmdShowMessage}" HorizontalAlignment="Left" Margin="342,62,0,0" VerticalAlignment="Top" Width="128"/>
    </Grid>
</Window>

三個 RadioButton 的GroupName 設為一樣的名字,IsChecked 也 Binding 到同一個 Property,Mode=TwoWay,最後再加上 Command 和 CommandParameter ,並在不同的 RadioButton 指定不同的 CommandParameter 好讓 ViewModel 區別選到哪一個 RadioButton.

下面是Converter:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace ViewModel
{
    public class MyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //value是radio接到binding變數的值後,來呼叫converter
            //converter負責判定接到的值是代表true還是false
            if (value == null || parameter == null)
                return false;
            string checkvalue = value.ToString();
            string targetvalue = parameter.ToString();
            bool r = checkvalue.Equals(targetvalue,
                StringComparison.InvariantCultureIgnoreCase);
            return r;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //value 是目前 radiobutton 的 true/false
            //在這裡把 parameter 傳回 View-Model
            if (value == null || parameter == null)
                return null;
            bool usevalue = (bool)value;

            if (usevalue)
                return parameter.ToString();

            return null;
        }
    }
}

利用 Parameter 來判斷所選的 RadioButton 。

再配合一下 Command :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace ViewModel
{
    public class ShowMsgCmdClass : ICommand
    {
        ViewModelClass vm;
        public ShowMsgCmdClass(ViewModelClass fvm)
        {
            vm = fvm;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            vm.ShowMsg();
        }
    }
}

連接 ViewModel :


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace ViewModel
{
    public class ViewModelClass : INotifyPropertyChanged
    {
        string currentOption;

        public string CurrentOption
        {
            get
            {
                return currentOption;
            }
            set
            {
                if (value != null) //要判斷一下是否為 null,否則選了A,又選B時,最後一個回傳的會是A的值,這樣就抓不到了。
                    currentOption = value;
            }
        }

        ShowMsgCmdClass cmdShowMessage;

        public ShowMsgCmdClass CmdShowMessage
        {
            get { return cmdShowMessage; }
            set { cmdShowMessage = value; }
        }
        public ViewModelClass()
        {
            cmdShowMessage = new ShowMsgCmdClass(this);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string prop)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(prop));
        }

        public void ShowMsg()
        {
            System.Windows.MessageBox.Show("You Select " + currentOption);
        }
    }
}

這樣就可以了~