我在 WPF 中有一个组合框,我设置了 Is Editable="true",它允许我在组合框中输入任何文本。我想限制用户在数据源之外输入文本。
Xaml:
<ComboBox Name="service" Margin="0,0,0,4"
IsEditable="True"
Grid.Column="1"
Grid.ColumnSpan="2" Grid.Row="4"
SelectedValuePath="Id"
DisplayMemberPath="Service"
SelectedValue="{Binding Controller.Service1}"
ItemsSource="{Binding}" />
C#:
System.Data.DataView vw = tableAdapterServices.GetData().DefaultView;
service.ItemsSource = vw;
service.SelectedIndex = 0;
我不想允许用户输入数据源中不存在的文本,或者在用户输入任何其他文本时处理它。
更新:
感谢@Vishal 的解决方案,LostFocus 事件正在处理该问题,但它引发了另一个问题。我有一个按钮,用于将组合框值与其他文本框值一起提交到服务器。我在丢失焦点事件的组合框中设置默认值。但如果在组合框中添加了数据源值以外的其他值,我需要阻止按钮单击事件。
最佳答案
您可以在 Lostfocus 事件中检查 selectedIndex :
private void ComboBox_LostFocus(object sender, EventArgs e)
{
if(((ComboBox)sender).SelectedIndex == -1)
{
//Text entered by user is not a part your ItemsSource's Item
SaveButton.IsEnabled = false;
}
else
{
//Text entered by user is a part your ItemsSource's Item
SaveButton.IsEnabled = true;
}
}
关于c# - 当输入的文本不是数据源的一部分时处理 WPF 可编辑组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24930147/