我正在尝试将文本框绑定到字符串变量,同时我想将 ComboBox 绑定到列表。
<Window
x:Class="Assignment2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:validators="clr-namespace:Assignment2"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="109,103,0,0" Name="StringComboBox" VerticalAlignment="Top" Width="120" SelectionChanged="SelectionChanged">
<ComboBox.ItemsSource>
<Binding Path="ListString" Mode="TwoWay" UpdateSourceTrigger="LostFocus"></Binding>
</ComboBox.ItemsSource>
</ComboBox>
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,51,250,0" Name="inputTextBox" VerticalAlignment="Top" Width="154" LostFocus="inputTextBox_LostFocus">
<TextBox.Text>
<Binding Path="Name1" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validators:RequiredFieldValidator ErrorMessage="This field Should not be empty"></validators:RequiredFieldValidator>
<validators:OnlyCharacterValidation ErrorMessage="Only characters allowed"></validators:OnlyCharacterValidation>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>
后面的代码是:
public partial class MainWindow : Window, INotifyPropertyChanged
{
string _name = "Default Value";
public ObservableCollection<string> ListString;
public string Name1
{
get { return _name; }
set
{
_name = value;
}
}
public MainWindow()
{
ListString = new ObservableCollection<string>();
ListString.Add("AAA");
ListString.Add("BBB");
ListString.Add("CCC");
ListString.Add("DDD");
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private void inputTextBox_LostFocus(object sender, RoutedEventArgs e)
{
OnPropertyChanged("Name1");
}
}
}
我似乎无法同时绑定 Combobox 和 Textbox。我已经尝试了很多解决方案。但无论哪种方式,只有其中一种有效。有什么简单的解决方案吗?