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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sdhongjun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值