datagrid中的组合框不包含可见的值

时间:2018-08-01 05:44:21

标签: c# wpf search combobox datagrid

我有一个问题,我需要在datagrid内具有搜索字段。我已经通过combobox做到了,问题是combobox保留了它的值,但是没有像图片上那样向用户显示它,但是当我单击返回到combobox列中的填充行时,值显示了,当我单击其他任何地方时,combobox为空。

图片1: Filled Data Grid 图片2 New row and the value disappeared

XAML:

<Window x:Class="DGdatum.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:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
    xmlns:local="clr-namespace:DGdatum" 
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    mc:Ignorable="d"
    Title="Datum_test" Height="450" Width="800">


<Grid Name="tab">
    <Grid.RowDefinitions>
        <RowDefinition Height="200"/>
        <RowDefinition Height="100"/>
    </Grid.RowDefinitions>
    <DataGrid Grid.Row="0" x:Name="dgusers" AutoGenerateColumns="False" AddingNewItem="pridejItem" CanUserAddRows="False" Margin="10,10,10,0" PreviewKeyDown="btnclick" RowEditEnding="dgusers_RowEditEnding">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding jmeno}" />
            <DataGridTemplateColumn Header="Datum">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DatePicker x:Name="kalendar" SelectedDate="{Binding datum}"  BorderThickness="0" SelectedDateChanged="ukaz" Loaded="kalendar_Loaded" KeyUp="kalendar_KeyUp"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>  
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="autof" x:Name="ahoj">
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox x:Name="search" IsEditable="True" IsTextSearchEnabled="True"  SelectedItem="{Binding material}" IsTextSearchCaseSensitive="False" Loaded="search_Loaded" SelectionChanged="search_SelectionChanged" AutomationProperties.IsOffscreenBehavior="Default"/>
                        <!--<toolkit:AutoCompleteBox x:Name="Autofille" ItemsSource="{Binding polozky, Mode=TwoWay}" FilterMode="Contains"  MinimumPrefixLength="1"/>-->
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    <StackPanel Grid.Row="1">

        <Button  Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        <Button x:Name="pridej" Grid.Row="1" Content="+" FontSize="16" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="pridej_Click" />
    </StackPanel>

</Grid>

后面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DGdatum
{
/// <summary>
/// Interakční logika pro MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        dgusers.CanUserAddRows = true;
        dgusers.ItemsSource = uziv;

        napllist();


    }

    List<Users> uziv = new List<Users>();
    DateTime date = DateTime.Now;
    DateTime ted = DateTime.Now;
    string mat = null;
    DatePicker dp;
    DatePicker cal;
    List<string> polozky = new List<string>();
    ComboBox combo;


    public class Users
    {
        public string jmeno { get; set; }
        public DateTime datum { get; set; }
        public string material { get; set; }
        public override string ToString()
        {
            return string.Format("{0} \n {1}\n{2}", jmeno, datum, material);
        }
    }

    private void pridejItem(object sender, AddingNewItemEventArgs e)
    {
        e.NewItem = new Users
        {
            jmeno = "",
            datum = date,
            material = mat
        };

    }

    private void ukaz(object sender, SelectionChangedEventArgs e)
    {
        cal = sender as DatePicker;            
        if (cal.SelectedDate.Value.Year != ted.Year || cal.SelectedDate.Value.Month != ted.Month || cal.SelectedDate.Value.Day != ted.Day)
        {
            date = cal.SelectedDate.Value;                
        }
        else
        {                
            date = ted;                
        }            
    }

    private void btnclick(object sender, KeyEventArgs e)
    {
        var uiElement = e.OriginalSource as UIElement;
        if (e.Key == Key.Enter && uiElement != null)
        {
            e.Handled = true;
            uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }     

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        vypis();
    }

    private void kalendar_Loaded(object sender, RoutedEventArgs e)
    {
        dp = sender as DatePicker;            
    }

    private void kalendar_KeyUp(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
        {
            dp = sender as DatePicker;
            if (dp != null)
            {

            }
        }
    }

    private void dgusers_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
    {

    }

    private void vypis()
    {
        foreach (Users x in uziv)
        {
            MessageBox.Show(x.ToString());
        }
    }     

    private void dgusers_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show("bla");
    }
    public void napllist()
    {
        polozky.Add("auto");
        polozky.Add("stul");
        polozky.Add("motorka");
        polozky.Add("jablko");
        polozky.Add("autodlak");
        polozky.Add("drap");
        polozky.Add("mrakodrap");
        polozky.Add("letadlo");
        polozky.Add("nuzy");
        polozky.Add("duke-nukem");
        polozky.Add("loď");
    }

    private void pridej_Click(object sender, RoutedEventArgs e)
    {


    }

    private void search_Loaded(object sender, RoutedEventArgs e)
    {
       combo = sender as ComboBox;
        combo.ItemsSource = polozky;

    }

    private void search_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        combo = sender as ComboBox;
        if(combo.SelectedItem != null)
        {
            mat = combo.SelectedItem.ToString();

        }
        //combo.Text = combo.SelectedItem.ToString();

    }

    private void search_PreviewKeyDown(object sender, KeyEventArgs e)
    {

    }

    private void dgusers_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        //MessageBox.Show(combo.Text);
        //combo.SetCurrentValue(ComboBox.TextProperty, "ahoj");
    }
}
}

1 个答案:

答案 0 :(得分:0)

您需要在CellTemplate旁边添加一个CellEditingTemplate。 我认为这可以完成工作:

<DataGridTemplateColumn Header="autof" x:Name="ahoj">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding material}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox x:Name="search" IsEditable="True" IsTextSearchEnabled="True"  SelectedItem="{Binding material}" IsTextSearchCaseSensitive="False" Loaded="search_Loaded" SelectionChanged="search_SelectionChanged" AutomationProperties.IsOffscreenBehavior="Default"/>
            <!--<toolkit:AutoCompleteBox x:Name="Autofille" ItemsSource="{Binding polozky, Mode=TwoWay}" FilterMode="Contains"  MinimumPrefixLength="1"/>-->
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

如果要使用“空白”项目创建新行,则可能需要修改pridejItem函数:

private void pridejItem(object sender, AddingNewItemEventArgs e)
{
    e.NewItem = new Users
    {
        jmeno = "",
        datum = date,
        material = ""
    };
}