[英]C# Update Combobox text after SelectedItemChange
我有一个组合框,我希望实际显示的文本始终保持不变。
我希望用户选择一个项目,然后将其传入,但是组合框上的实际文本保持不变。
在
FileBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
如果我发现选择了哪个项目
if (((ComboBox)sender).SelectedItem != null)
{
if (((ComboBox)sender).SelectedItem.ToString() == "New File")
{
}
}
(我将在稍后处理)
然后,我尝试将文本更新为“文件”。
我尝试了许多似乎无效的方法。
我只是尝试做
FileBox.text = "File";
this.Dispatcher.Invoke(() =>
{
FileBox.Text = "File";
});
FileBox.SelectedItem = "File";
调试时,实际上似乎更新了.Text属性,但似乎在事件结束时被覆盖了。 为了测试我有一个按钮,它可以:
var text = FileBox.Text;
FileBox.Text = "File";
当我选择“新文件”时,var文本==新文件
而且这里的FileBox.Text代码可以正常工作并将其更新回File
我是否需要在SelectionChanged事件之外再次设置文本,如果是的话,我该怎么做?
谢谢
编辑
我不认为这是发布内容的重复,因为他希望在选择某项内容后消失默认值,我希望它重新出现
该方法实际上并不理想,您应该使用MVVM模式,但这是我对您的问题的回答,希望对您有所帮助。
<ComboBox x:Name="FileBox"
SelectedIndex="0"
SelectionChanged="FileBox_OnSelectionChanged"
Width="180" Height="50" >
Code-behind
private void FileBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var fileBox = sender as ComboBox;
if (fileBox != null)
{
var selectedItem = fileBox.SelectedItem;
// get the selected item.
Debug.WriteLine(selectedItem);
fileBox.SelectionChanged -= FileBox_OnSelectionChanged;
fileBox.SelectedIndex = 0;
fileBox.SelectionChanged += FileBox_OnSelectionChanged;
}
}
假设这是您填充控件的方式:
private void PopulateFileData()
{
FileDataList = new List<FileData>
{
new FileData{ FileName = "Files", Path = "" },
new FileData{ FileName = "File 123", Path = @"c:\file1.txt" },
new FileData{ FileName = "File 456", Path = @"c:\file2.txt" }
};
}
private void FillComboBox()
{
foreach (FileData file in FileDataList)
{
FileBox.Items.Add(file.FileName);
}
}
检查您的输出窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.