c# - WPF、Caliburn Micro 和 Dapper - Datagrid 复选框绑定(bind)

标签 c# wpf mvvm dapper caliburn.micro

我在创建 DataGrid 的 WPF 项目中使用 Caliburn Micro 和 Dapper我用 SQL Server 数据库表中的数据填充它。请考虑以下代码片段:

ChangesModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PTSRDesktopUI.Models
{
    //public class for all changes attributes
    public class ChangesModel
    {
        public int ID { get; set; }
        public string Facility { get; set; }
        public string Controller { get; set; }
        public string ParameterName { get; set; }
        public string OldValue { get; set; }
        public string NewValue { get; set; }
        public DateTime ChangeDate { get; set; }
        public bool Validated { get; set; }
        public DateTime ValidationDate { get; set; }
    }
}

OverviewView.xaml
<!--Datagrid Table-->
<DataGrid Grid.Row="1" x:Name="Changes" CanUserAddRows="False" AutoGenerateColumns="False" HorizontalAlignment="Stretch">
    <DataGrid.Columns>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="Facility" Binding="{Binding Path=Facility}"/>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="Controller" Binding="{Binding Path=Controller}"/>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="Parameter" Binding="{Binding Path=ParameterName}"/>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="Old Value" Binding="{Binding Path=OldValue}"/>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="New Value" Binding="{Binding Path=NewValue}"/>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="Changed Date" Binding="{Binding Path=ChangeDate, 
                            StringFormat='{}{0:dd.MM HH:mm}'}"/>
        <DataGridTemplateColumn CellStyle="{StaticResource DataGridCellCentered}" 
                                Header="Validated" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate >
                    <CheckBox IsChecked="{Binding Path=Validated}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn CellStyle="{StaticResource DataGridCellCentered}" IsReadOnly="True" 
                            Header="Validation Date" Binding="{Binding Path=ValidationDate, 
                            StringFormat='{}{0:dd.MM HH:mm}'}"/>
        <DataGridTemplateColumn CellStyle="{StaticResource DataGridCellCentered}" Header="Validate">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button x:Name="Validate_Btn" cal:Message.Attach="Validate">Validate</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

概述ViewModel.cs
using Caliburn.Micro;
using PTSRDesktopUI.Helpers;
using PTSRDesktopUI.Models;

namespace PTSRDesktopUI.ViewModels
{
    public class OverviewViewModel : Screen
    {

        //Create new Bindable Collection variable of type ChangesModel
        public BindableCollection<ChangesModel> Changes { get; set; }


        public OverviewViewModel()
        {

            //Create connection to DataAccess class
            DataAccess db = new DataAccess();

            //get the changes from DataAccess function and store them as a bindable collection in Changes
            Changes = new BindableCollection<ChangesModel>(db.GetChanges());

        }

        //Validate_Btn click event
        public void Validate()
        {
           //Some Code        
        }

    }
}

数据访问.cs
//Function to get all changes from database using stored procedures
public List<ChangesModel> GetChanges()
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(DBHelper.CnnVal("ptsrDB")))
    {
        var output = connection.Query<ChangesModel>("dbo.getChanges").ToList();
        return output;
    }
}

我使用了一个名为 getChanges 的存储过程从 SQL Server 获取数据。数据显示出来,一切正常。我现在想做的是:
首先我想要 Validate_Btn仅在 CheckBox 所在的行上可见未选中。其次,如果用户点击Validate_Btn ,我想更改CheckBox要检查,使按钮不可见并使用 DataAccess 类中的存储过程触发一个新函数,以更新 Validated 的 bool 值在数据库表中。任何人有任何想法我怎么能做到这一点?

最佳答案

解决第一部分显示和隐藏Button基于是否 CheckBox被检查,你应该首先实现INotifyPropertyChanged您的ChangesModel中的界面上课并提高PropertyChanged Validated 时的事件属性设置:

public class ChangesModel : INotifyPropertyChanged
{
    public int ID { get; set; }
    public string Facility { get; set; }
    public string Controller { get; set; }
    public string ParameterName { get; set; }
    public string OldValue { get; set; }
    public string NewValue { get; set; }
    public DateTime ChangeDate { get; set; }

    private bool _validated;
    public bool Validated
    {
        get { return _validated; }
        set { _validated = value; NotifyPropertyChanged(); }
    }

    public DateTime ValidationDate { get; set; }

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

然后您可以绑定(bind) ButtonVisibility Validated 的属性(property)source 属性并使用转换器在 bool 之间进行转换值和 Visibility枚举值:
<DataGridTemplateColumn Header="Validate">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <DataTemplate.Resources>
                <BooleanToVisibilityConverter x:Key="converter" />
            </DataTemplate.Resources>
            <Button x:Name="Validate_Btn" cal:Message.Attach="Validate"
                    Visibility="{Binding Validated, Converter={StaticResource converter}}">Validate</Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

您可能还想设置 UpdateSourcePropertyTriggerCheckBox立即设置源属性的绑定(bind):
<CheckBox IsChecked="{Binding Path=Validated, UpdateSourceTrigger=PropertyChanged}" />

为您的Validate()要在单击按钮时被调用,您可以绑定(bind) Bind.Model附加属性到 View 模型:
<Button x:Name="Validate"
        cal:Bind.Model="{Binding DataContext, 
            RelativeSource={RelativeSource AncestorType=DataGrid}}">Validate</Button>

组合绑定(bind)需要指定 Visibility 的来源捆绑:
<Button x:Name="Validate"
    Visibility="{Binding DataContext.Validated, 
       Converter={StaticResource converter}, RelativeSource={RelativeSource AncestorType=DataGridCell}}"
    cal:Bind.Model="{Binding DataContext, RelativeSource={RelativeSource AncestorType=DataGrid}}">Validate</Button>

关于c# - WPF、Caliburn Micro 和 Dapper - Datagrid 复选框绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60071677/

相关文章:

c# - PostSharp:使用 OnMethodInvocationAspect 时删除了自定义属性

.net - TabControl中的WPF MVVM Light主-详细信息,使用消息传递所选项目

c# - 签署应用程序时出现 System.IO.FileLoadException

c# - 分页搜索结果

c# - Orchard CMS 如何在 Orchard CMS 中传输我的 ASP.NET MVC 布局(页眉、页脚等)/主题?

c# - WPF、PreviewKeyDown 事件和下划线字符

c# - 从子 ViewModel 到父 ViewModel 的属性返回值

wpf - 如何在 wpf 中为 Storyboard 设置参数?

wpf - 在 MVVM 中,拖动完成后打开上下文菜单

c# - 在 ASP.NET 中获取服务器的 IP 地址?