簡體   English   中英

雙擊WPF數據網格中的單個單元格,如何更改它的值?

[英]How do I change the value of an individual cell in a WPF datagrid when it is double clicked?

我有一個數據網格,其中列出了幾件事情的狀態並顯示“ True”或“ False”。 當我雙擊一個單元格時,我想切換該單元格顯示的內容。 我已經嘗試為我的數據網格使用許多屬性,例如currentItem,SelectedItem,SelectedValue和SelectedUnit,但是這些都不起作用。

<DataGrid x:Name="dataGrid1" IsReadOnly="True" IsManipulationEnabled="False" Width="250" Height="468"  Margin="795,15,18,15" 
          VerticalAlignment="Top" AutoGenerateColumns="False" CanUserAddRows="False" MouseDoubleClick="DoubleClick" 
          ItemsSource="{Binding Availability}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Number" Binding="{Binding Key, UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
        <DataGridTextColumn Header="Status1" Binding="{Binding Value1, UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
        <DataGridTextColumn Header="Status2" Binding="{Binding Value2, UpdateSourceTrigger=PropertyChanged}" Width="*"/>
    </DataGrid.Columns>
</DataGrid>

這是我背后的代碼中的事件:

private void DoubleClick(object sender, MouseButtonEventArgs e)
{
    if (dataGrid1.SelectedItem == null) return;

    if (dataGrid1.CurrentItem == "True" )
    {
        dataGrid1.CurrentItem = "False";
    }
    else if (dataGrid1.CurrentItem == "False")
    {
        dataGrid1.CurrentItem = "True";
    }
}

如果您想知道雙擊哪個DataGridCell,則必須將其添加到XAML中:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <EventSetter Event="MouseDoubleClick" Handler="dataGrid1_CellDoubleClick" />
    </Style>
</DataGrid.CellStyle>

然后在您的代碼隱藏中,處理事件:

private void dataGrid1_CellDoubleClick(object sender, RoutedEventArgs e)
{
    var cell = sender as DataGridCell;

    // Do stuff with your cell
}

問題是...您的DataGrid和列是數據綁定的,因此您對單元格內容所做的大多數操作都不會反映在實際數據中。

我說“ ”,是因為實際上您可以同時更改單元格文本和數據綁定屬性的值...但是它很臟,實際上並不屬於視圖。

private void dataGrid1_CellDoubleClick(object sender, RoutedEventArgs e)
{
    var cell = sender as DataGridCell;

    if (cell != null && cell.Content is TextBlock)
    {
        var textBlock = cell.Content as TextBlock;
        textBlock.SetCurrentValue(TextBlock.TextProperty, "put your text here");
        var binding = BindingOperations.GetBindingExpression(textBlock, TextBlock.TextProperty);
        binding.UpdateSource();
    }
}

為此,您必須在DataGridTextColumn綁定上設置Mode=TwoWay (盡管它可能已經是默認模式,但我不記得了)。 而且,它不能與其他類型的列一起使用。

但是...正如我所說,此解決方案很臟,您希望在視圖模型中使用這種邏輯。

最簡單的方法是從視圖模型中公開一個方法,您可以在代碼中調用該方法,然后傳遞一些參數,例如行的數據項和列的屬性名。

private void dataGrid1_CellDoubleClick(object sender, RoutedEventArgs e)
{
    var cell = sender as DataGridCell;

    if (cell != null)
    {
        (this.DataContext as MyViewModel).DoStuff(cell.DataContext, cell.Column.SortMemberPath);
    }
}

暫無
暫無

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

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