在我的WPF應用程序中,我有一個數據綁定TextBox
和一個數據綁定ItemsControl
。 ItemsControl
的內容取決於TextBox
的內容。我希望能夠在TextBox
中鍵入一個值,然後按Tab鍵並輸入ItemsControl
中的第一項(由TextBox
中的值創建)。我遇到的問題是在WPF在ItemsControl
中創建模板項目之前評估選項卡操作。下面的代碼演示了此問題:WPF Tab Into Databound ItemsControl
<Window x:Class="BindingExample.Window1" x:Name="SelfControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:BindingExample" Title="Window1" Height="300" Width="400">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:ChildClass}">
<TextBox Text="{Binding Value}" />
</DataTemplate>
</Window.Resources>
<StackPanel DataContext="{Binding ElementName=SelfControl}" Focusable="False">
<Label Content="Options: A, B, C" />
<TextBox Text="{Binding Object.Value}" />
<ItemsControl Margin="16,0,0,0" ItemsSource="{Binding Object.Children}" Focusable="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<TextBox Text="Box2" />
</StackPanel>
</Window>
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace BindingExample
{
public partial class Window1
{
public static readonly DependencyProperty ObjectProperty = DependencyProperty.Register("Object", typeof(ParentClass), typeof(Window1));
public ParentClass Object
{
get { return GetValue(ObjectProperty) as ParentClass; }
set { SetValue(ObjectProperty, value); }
}
public Window1()
{
InitializeComponent();
Object = new ParentClass();
}
}
public class ParentClass : INotifyPropertyChanged
{
private string value;
public string Value
{
get { return value; }
set { this.value = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Children")); }
}
public IEnumerable<ChildClass> Children
{
get
{
switch (Value.ToUpper())
{
case "A": return new ChildClass[] { "A-1", "A-2", "A-2" };
case "B": return new ChildClass[] { "B-1", "B-2", "B-3" };
case "C": return new ChildClass[] { "C-1", "C-2", "C-2" };
default: return new ChildClass[] { "Unknown" };
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class ChildClass
{
public string Value { get; set; }
public static implicit operator ChildClass(string value) { return new ChildClass { Value = value }; }
}
}
在這段代碼中,我想輸入「A」到第一TextBox
,按Tab鍵,並有重點轉移到孩子TextBox
文本「A-1」。相反,焦點跳轉到文本框「文本2」。我如何實現我在這裏尋找的行爲?
注:作爲朱利安波林所指出的,可以通過對TextBox
到PropertyChanged
切換UpdateSourceTrigger
,使這項工作。然而,這隻適用於「如鍵入」綁定的情況。在我的情況下,我還想通過一次按鍵來設置值和標籤。有沒有辦法強制ItemsControl按需創建其模板化項目?
This works。然而,理想情況下,我希望在控件失去焦點時發生綁定,而不是在用戶輸入時發生。 – 2009-07-20 22:51:29