【发布时间】:2016-05-13 17:21:26
【问题描述】:
我有以下编码,我将 CheckBox 和 TextBlock 绑定到一个 DataGridTemplateColumn 中。
当我单击单元格本身以编辑其中的文本时,是否可以使用复选框和文本框来编辑单元格?我仍然希望能够在编辑文本块中的文本的同时将我的 CheckBox 设置为 true 或 false。
这是我的代码:
private void btnFeedbackSelectSupplier_Click(object sender, RoutedEventArgs e)
{
DataGridTemplateColumn columnFeedbackSupplier = new DataGridTemplateColumn();
columnFeedbackSupplier.Header = "Supplier";
columnFeedbackSupplier.CanUserReorder = true;
columnFeedbackSupplier.CanUserResize = true;
columnFeedbackSupplier.IsReadOnly = false;
//My stack panel where I will host the two elements
var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
DataTemplate cellTemplate = new DataTemplate();
//Where I create my checkbox
FrameworkElementFactory factoryCheck = new FrameworkElementFactory(typeof(CheckBox));
Binding bindCheck = new Binding("TrueFalse");
bindCheck.Mode = BindingMode.TwoWay;
factoryCheck.SetValue(CheckBox.IsCheckedProperty, bindCheck);
stackPanel.AppendChild(factoryCheck);
//Where I create my textblock
FrameworkElementFactory factoryText = new FrameworkElementFactory(typeof(TextBlock));
Binding bindText = new Binding("Supplier");
bindText.Mode = BindingMode.TwoWay;
factoryText.SetValue(TextBlock.TextProperty, bindText);
stackPanel.AppendChild(factoryText);
cellTemplate.VisualTree = stackPanel;
columnFeedbackSupplier.CellTemplate = cellTemplate;
DataGridTextColumn columnFeedbackSupplierItem = new DataGridTextColumn();
columnFeedbackSupplier.Header = (cmbFeedbackSelectSupplier.SelectedItem as DisplayItems).Name;
dgFeedbackAddCost.SelectAll();
IList list = dgFeedbackAddCost.SelectedItems as IList;
IEnumerable<ViewQuoteItemList> items = list.Cast<ViewQuoteItemList>();
var collection = (from i in items
let a = new ViewQuoteItemList { Item = i.Item, Supplier = i.Cost, TrueFalse = false }
select a).ToList();
dgFeedbackSelectSupplier.Columns.Add(columnFeedbackSupplier);
dgFeedbackSelectSupplier.ItemsSource = collection;
}
我现在的外观示例以及我想如何编辑单元格内的 R12 值,同时仍然能够将复选框设置为 true 或 false。
【问题讨论】:
-
为什么不用
TextBox而不是TextBlock? -
我知道有人会问这个问题:P 因为
TextBox看起来很傻,因为它不想扩展我的列长度的整个宽度 -
只需设置
HorizontalAlignment="Stretch"的属性TextBox -
factoryText.Text = HorizontalAlignment.Stretch;喜欢这样吗? 0_o -
如果
factoryText是TextBox,那么textBox.HorizontalAlignment = HorizontalAlignment.Stretch;
标签: c# wpf xaml checkbox datagrid