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

猜你喜欢

转载自blog.csdn.net/sdhongjun/article/details/83272736
今日推荐