【发布时间】:2021-12-27 20:47:33
【问题描述】:
我正在尝试编写一个 WPF 应用程序,该应用程序在一个用户控件中接受用户输入,然后在另一个用户控件中的另一个页面上显示它。 为了在 SetupLocation 中捕获用户输入,我使用了一个 TextBox,它通过 TwoWay 绑定到 LocationSettings 对象,该对象当前只有一个属性 LocationName。 另一个 Page 包含一个名为 ShowResult 的 UserControl,它具有与 LocationSettings 对象的 OneWay 绑定。
我正在使用 .NET Framework v4.7.2 和 Visual Studio 2019。
但是:
- 在 SetupLocation 中输入的值永远不会显示在结果页面中(结果页面显示我在 LocationSettings 的构造函数中选择分配给 LocationName 的任何默认值)。
- 无论我是否按下“设置”按钮,在 SetupLocation 中输入的值都会被保留。似乎 UpdateSourceTrigger 参数被忽略了,因为当我使用 LostFocus 作为 UpdateSourceTrigger 的参数时,我得到了完全相同的结果。
我错过了什么?
这是 UserControl 的 XAML,称为 SetupLocation(用于输入数据):
<StackPanel Orientation="Vertical" Margin="10"
VerticalAlignment="Top">
<StackPanel.Resources>
<ObjectDataProvider x:Key="locationInput" ObjectType="{x:Type classes:LocationSettings}"/>
</StackPanel.Resources>
<TextBox x:Name="LocationName"
<TextBox.Text>
<Binding Source="{StaticResource locationInput}"
Path="LocationName"
Mode="TwoWay"
UpdateSourceTrigger="Explicit"/>
</TextBox.Text>
</TextBox>
<Button x:Name="addParameters"
Content="Set"
Click="addParameters_Click"/>
</StackPanel>
SetupLocation 的代码:
public partial class SetupLocation : UserControl
{
public SetupLocation()
{
InitializeComponent();
}
private void addParameters_Click(object sender, RoutedEventArgs e)
{
BindingExpression be = LocationName.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
}
UserControl 的 XAML(与 SetupLocation 不同的页面的一部分)ShowResult 应该显示在 SetupLocation 中输入的内容:
<StackPanel>
<StackPanel.Resources>
<ObjectDataProvider x:Key="locationInput" ObjectType="{x:Type classes:LocationSettings}"/>
</StackPanel.Resources>
<Label FontSize="18" Foreground="Green">
<Label.Content>
<Binding Source="{StaticResource locationInput}"
Path="LocationName"
/>
</Label.Content>
</Label>
</StackPanel>
包含我需要在两个用户控件之间传递的 LocationName 变量的 LocationSettings 类。
public class LocationSettings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _locationName;
public string LocationName
{
get {
return _locationName;
}
set {
_locationName = value;
OnPropertyChanged();
}
}
public LocationSettings()
{
// _locationName = "Nowhere really";
}
protected void OnPropertyChanged([CallerMemberName] string tmp = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(tmp));
}
}
MainWindow.xaml:
public partial class MainWindow : Window
{
public LocationSettings DefaultSettings;
public MainWindow()
{
InitializeComponent();
DefaultSettings = new LocationSettings();
}
【问题讨论】:
标签: c# wpf data-binding