gpt4 book ai didi

c# - 如何将值设置为 WPF 中的自定义 DataGrid 绑定(bind)列

转载 作者:行者123 更新时间:2023-11-30 18:07:57 25 4
gpt4 key购买 nike

因为无法将值粘贴到 DataGridTemplateColumn 中。我发现了一些关于创建我自己的从 DataGridBoundColumn 派生的列类的建议。下面的示例在不使用模板的情况下将 DatePicker 添加到列。

但是,此示例不允许我使用 DatePicker 手动设置值,我不确定为什么。我在想绑定(bind)有什么问题。它将加载我最初绑定(bind)到它的日期值,所以它已经到一半了。

有趣的是,使用其他一些帮助程序类我也能够粘贴日期,这是最初的目的。我只是不想破坏其他任何东西。 :-)

关于如何使日期选择器选择的值正确绑定(bind)的任何想法?

class MyDateColumn : DataGridBoundColumn 
{
public string DateFormat { get; set; }
protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue)
{
DatePicker dp = editingElement as DatePicker;
if (dp != null)
{
dp.SelectedDate = DateTime.Parse(uneditedValue.ToString());
}
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
DatePicker dp = new DatePicker();
Binding b = new Binding();
Binding bb = this.Binding as Binding;
b.Path = bb.Path;
b.Source = DatePicker.SelectedDateProperty;
if (DateFormat != null)
{
DateTimeConverter dtc = new DateTimeConverter();
b.Converter = dtc;
b.ConverterParameter = DateFormat;
}
dp.SetBinding(DatePicker.SelectedDateProperty, this.Binding);

return dp;
}

protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
TextBlock txt = new TextBlock();
Binding b = new Binding();
Binding bb = this.Binding as Binding;
b.Path = bb.Path;
b.Source = cell.DataContext;

if (DateFormat != null)
{
DateTimeConverter dtc = new DateTimeConverter();
b.Converter = dtc;
b.ConverterParameter = DateFormat;
}
txt.SetBinding(TextBlock.TextProperty, this.Binding);
return txt;
}

protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
DatePicker dp = editingElement as DatePicker;
if (dp != null)
{
DateTime? dt = dp.SelectedDate;
if (dt.HasValue)
return dt.Value;
}
return DateTime.Today;
}

protected override bool CommitCellEdit(FrameworkElement editingElement)
{
DatePicker dp = editingElement as DatePicker;
dp.SelectedDate = DateTime.Today.AddYears(1);

return true;
//return base.CommitCellEdit(editingElement);
}
}

最佳答案

解决方案是修改 CommitCellEdit()...

    protected override bool CommitCellEdit(FrameworkElement editingElement)
{
DatePicker dp = editingElement as DatePicker;
DateTime dt;
try
{
dt = Convert.ToDateTime(dp.Text);
dp.SelectedDate = dt;
}
catch (FormatException)
{
dp.Text = String.Empty;
}


BindingExpression binding = editingElement.GetBindingExpression(DatePicker.SelectedDateProperty);
if (binding != null)
binding.UpdateSource();
return true;
//return base.CommitCellEdit(editingElement);
}

原始代码和帮助来自以下链接...

http://leeontech.wordpress.com/2009/01/21/creating-datagriddatecolumn-for-datagrid/#comment-1033

感谢 Lee 创建示例和帮助!

关于c# - 如何将值设置为 WPF 中的自定义 DataGrid 绑定(bind)列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com