Ben*_*ale 81
这MVVM
是获得所需行为的基本合规方式:
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox Margin="30,5,30,5"
IsEditable="True"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
Text="{Binding NewItem, UpdateSourceTrigger=LostFocus}"/>
<TextBox Margin="30,5,30,5" />
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
MainWindow.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string _selectedItem;
private ObservableCollection<string> _items = new ObservableCollection<string>()
{
"One",
"Two",
"Three",
"Four",
"Five",
};
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
public IEnumerable Items
{
get { return _items; }
}
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
public string NewItem
{
set
{
if (SelectedItem != null)
{
return;
}
if (!string.IsNullOrEmpty(value))
{
_items.Add(value);
SelectedItem = value;
}
}
}
protected void OnPropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Run Code Online (Sandbox Code Playgroud)
我必须在窗口中放置另一个控件,因为我已经设置UpdateSourceTrigger
了Text
绑定的属性LostFocus
.如果窗口中没有其他控件,那么Combobox
永远不会失去焦点.
我更改了更新模式,因为默认更新模式Propertychanged
将为每次击键添加一个新项目.
EG如果您输入文本"Window",则以下内容将添加到您的收藏中:
W
Wi
Win
Wind
Windo
Window
Run Code Online (Sandbox Code Playgroud)
我会在 LostFocus 事件中处理它。
在这里您可以检查 SelectedItem 是否为空。如果是,则将 Text 的值添加到绑定列表并将 SelectedItem 设置为新项。
在 XAML 中:
<ComboBox Name="_list" LostFocus="LostFocus" IsEditable="True"/>
Run Code Online (Sandbox Code Playgroud)
在代码隐藏中:
private ObservableCollection<string> _names;
public MainWindow()
{
InitializeComponent();
_names = new ObservableCollection<string> {"Eric", "Phillip"};
_list.SetBinding(ItemsControl.ItemsSourceProperty, new Binding {Source = _names});
}
private void LostFocus(object sender, RoutedEventArgs e)
{
var comboBox = (ComboBox) sender;
if(comboBox.SelectedItem != null)
return;
var newItem = comboBox.Text;
_names.Add(newItem);
comboBox.SelectedItem = newItem;
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)
归档时间: |
|
查看次数: |
59492 次 |
最近记录: |