gpt4 book ai didi

wpf - 防止 WPF 组合框在 itemssource 更改时清除选择

转载 作者:行者123 更新时间:2023-12-05 00:09:18 24 4
gpt4 key购买 nike

我有一个用于名字的文本框、一个用于姓氏的文本框和一个用于显示名的组合框。显示名称是可编辑的,因此用户可以输入他们想要的任何内容。但是,组合框应显示选项列表。

当任一文本框更改时,组合框项目源会更新。但是,如果用户以前已选择 一个值,则 text 属性被清空。但是如果用户有 输入 在一个值中,文本属性仍然存在。如何防止文本值消隐?

这是我的代码:

<Window x:Class="MainWindow"
x:Name="MainApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<Grid DataContext="{Binding ElementName=MainApp}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0"
Text="{Binding FirstName}" />
<TextBox Grid.Row="1"
Text="{Binding LastName}" />
<ComboBox x:Name="MyCb" Grid.Column="1"
Grid.Row="2"
Text="{Binding TheName}"
ItemsSource="{Binding NameOptions}"
IsEditable="True" />
</Grid>
</Window>

Imports System.ComponentModel

Class MainWindow
Implements INotifyPropertyChanged

Public ReadOnly Property NameOptions As List(Of String)
Get
Dim result As New List(Of String)
result.Add(String.Format("{0} {1}", FirstName, LastName))
result.Add(String.Format("{1}, {0}", FirstName, LastName))
result.Add(String.Format("{1}, {0} MI", FirstName, LastName))
Return result
End Get
End Property

Public Property TheName As String

Private _firstName As String
Public Property FirstName As String
Get
Return _firstName
End Get
Set(value As String)
_firstName = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("FirstName"))
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("NameOptions"))
End Set
End Property

Private _lastname As String
Public Property LastName As String
Get
Return _lastname
End Get
Set(value As String)
_lastname = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("LastName"))
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("NameOptions"))
End Set
End Property

Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
End Class

最佳答案

在这里看到我的回答:
How to disable ItemsSource synchronization with Text property of ComboBox

public class ComboBox : System.Windows.Controls.ComboBox
{
private bool ignore = false;
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
if (!ignore)
{
base.OnSelectionChanged(e);
}
}

protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
ignore = true;
try
{
base.OnItemsChanged(e);
}
finally
{
ignore = false;
}
}
}

关于wpf - 防止 WPF 组合框在 itemssource 更改时清除选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866706/

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