1. 程式人生 > >WPF中DataGrid使用命令繫結按鈕列

WPF中DataGrid使用命令繫結按鈕列

注:本示例使用了MvvmLight控制元件。

1.定義Model

using GalaSoft.MvvmLight;

namespace WpfApplication5.Model
{
    public class DevItem : ObservableObject
    {
        public string IP { get; set; }
        public int CheckResult { get; set; }
    }
}

2.定義ViewModel

namespace WpfApplication5.ViewModel
{
/// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support.
/// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel
() { ////if (IsInDesignMode) ////{ //// // Code runs in Blend --> create design time data. ////} ////else ////{ //// // Code runs "for real" ////} DevItems = new ObservableCollection<DevItem>() { new DevItem() { IP = "192.168.2.5", CheckResult = 0 }, new DevItem() { IP = "192.168.2.6", CheckResult = 0 }, new DevItem() { IP = "192.168.2.7", CheckResult = 1 }, new DevItem() { IP = "192.168.2.8", CheckResult = 0 }, new DevItem() { IP = "192.168.2.8", CheckResult = 1 }, }; } private ObservableCollection<DevItem> _devItems; public ObservableCollection<DevItem> DevItems { get { return _devItems; } set { _devItems = value; RaisePropertyChanged(); } } private RelayCommand<DevItem> _cmdRecheck; public RelayCommand<DevItem> CmdRecheck { get { if (null == _cmdRecheck) { _cmdRecheck = new RelayCommand<DevItem>( (devItem) => { MessageBox.Show("Recheck item clicked."); }, (devItem) => { if (null == devItem) return false; //值為非1可以重新檢測 return devItem.CheckResult != 1; }); } return _cmdRecheck; } } } }

3.設定檢視

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication5"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <DataGrid VerticalAlignment="Stretch" x:Name="dgItems"
                  Height="Auto" IsReadOnly="False"
                  SelectionUnit="FullRow" SelectionMode="Extended" CanUserAddRows="False"
                  ItemsSource="{Binding DevItems}" Width="Auto" AutoGenerateColumns="False"
                  FontSize="16" AlternatingRowBackground="LightBlue"
                  AlternationCount="2" Margin="10, 10" Background="Transparent"
                  ScrollViewer.VerticalScrollBarVisibility="Visible">
            <DataGrid.Resources>
                <DataTemplate x:Key="btnCell">
                    <!--注意此處的設定方式-->
                    <Button Content="重新檢測" Command="{Binding Path=DataContext.CmdRecheck, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding}" Background="Yellow"/>
                </DataTemplate>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn Header="IP" Width="120*" Binding="{Binding IP, Mode=OneWay}" />
                <DataGridTextColumn Header="檢測結果" Binding="{Binding CheckResult, Mode=TwoWay}" Width="80*"/>
                <DataGridTemplateColumn Header="重新檢測" Width="80*" CellTemplate="{StaticResource btnCell}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

關鍵點

  • Command繫結語句
    Command="{Binding Path=DataContext.CmdRecheck, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
  • 按鈕命令物件引數的傳送
    CommandParameter="{Binding}"

參閱文章

https://www.grapecity.com/en/blogs/commandbinding-in-wpf-datagrid-part-ii