我试图让DataGridTextColumn
只允许上套管。
明显的做法是为CharacterCasing
Upper
设置EditingElementStyle
到TextBox
。只要您在开始输入之前进入编辑模式,但是如果您在单元格未处于编辑模式时开始输入,那么在TextBox
中输入的第一个字符是小写(在此之后,当单元格进入编辑模式时,一切都按预期工作。
我觉得这是一个错误,或者我错过了一些假设将CharacterCasing
设置为Upper
应该做的事情?有人为此修复或解决了这个问题吗?
问题可以像这样再现。只需将键盘焦点放在DataGrid
的第一个单元格中,然后按 a ,而不先进入编辑模式。看起来像这样
MainWindow.xaml
<DataGrid ItemsSource="{Binding MyList}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Test Character Casing"
Binding="{Binding Name}">
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="CharacterCasing" Value="Upper"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyList = new List<MyItem>();
MyList.Add(new MyItem { Name = "" });
MyList.Add(new MyItem { Name = "" });
this.DataContext = this;
}
public List<MyItem> MyList { get; set; }
}
public class MyItem
{
public string Name { get; set; }
}
答案 0 :(得分:3)
我很确定这是一个错误,我使用附加行为创建了一个解决方法。我没有设置CharacterCasing="Upper"
,而是使用behaviors:TextBoxUpperCaseBehavior.IsEnabled="True"
。
<Style TargetType="TextBox" x:Key="dataGridUpperCaseTextBoxStyle">
<Setter Property="behaviors:TextBoxUpperCaseBehavior.IsEnabled" Value="True"/>
</Style>
TextBoxUpperCaseBehavior
public static class TextBoxUpperCaseBehavior
{
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled",
typeof(bool),
typeof(TextBoxUpperCaseBehavior),
new UIPropertyMetadata(false, OnIsEnabledChanged));
[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static bool GetIsEnabled(TextBox comboBox)
{
return (bool)comboBox.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(TextBox comboBox, bool value)
{
comboBox.SetValue(IsEnabledProperty, value);
}
private static void OnIsEnabledChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = target as TextBox;
if ((bool)e.NewValue == true)
{
textBox.CharacterCasing = CharacterCasing.Upper;
textBox.TextChanged += textBox_TextChanged;
}
else
{
textBox.CharacterCasing = CharacterCasing.Normal;
textBox.TextChanged -= textBox_TextChanged;
}
}
private static void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox.Text.ToUpper() != textBox.Text)
{
textBox.Text = textBox.Text.ToUpper();
}
}
}