簡體   English   中英

WPF、Caliburn Micro 和 Dapper - Datagrid 復選框綁定

[英]WPF, Caliburn Micro and Dapper - Datagrid Checkbox binding

我在 WPF 項目中使用 Caliburn Micro 和 Dapper,在那里我創建了一個DataGrid ,我用 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; }
    }
}

概覽視圖.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的布爾值。 任何人有任何想法我怎么能做到這一點?

要解決第一部分根據CheckBox是否選中來顯示和隱藏Button的問題,您應該首先在ChangesModel類中實現INotifyPropertyChanged接口,並在設置Validated屬性時引發PropertyChanged事件:

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));
    }

}

然后,您可以將ButtonVisibility屬性綁定到Validated源屬性,並使用轉換器在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>

您可能還想在CheckBox綁定上設置UpdateSourcePropertyTrigger以立即設置源屬性:

<CheckBox IsChecked="{Binding Path=Validated, UpdateSourceTrigger=PropertyChanged}" />

為了在單擊按鈕時調用Validate() ,您可以將Bind.Model附加屬性綁定到視圖模型:

<Button x:Name="Validate"
        cal:Bind.Model="{Binding DataContext, 
            RelativeSource={RelativeSource AncestorType=DataGrid}}">Validate</Button>

組合綁定需要指定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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM