Xaml绑定在Application.Current下不起作用

3
所以我在App.xaml.cs中定义了两个全局属性Username和CurrentView,并在我的视图中绑定它们。 App.xaml.cs
 public partial class App : Application, INotifyPropertyChanged
 {
    public static object username;

    public object Username { get { return username; } set { username = value; } }

    public static Object currentView = new LoginView();

    public object CurrentView
    {
        get { return currentView; }
        set { currentView = value; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

我将它们绑定到不同的视图中。 MainView.xaml

    <Page  Content="{Binding CurrentView, Source={x:Static Application.Current}}">          
    </Page>

LoginView.xaml

    <TextBox  HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="165" Margin="218,159,0,0" Text="{Binding Path=Username, Source={x:Static Application.Current}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" />

在MainView中的绑定工作得非常好。它向我展示了我在app.xaml.cs中初始化为CurrentView的LoginView,并且当源更改时它会更改。

然而,与LoginView中的文本框绑定的用户名未更新。似乎无法找出问题所在。我已将UpdateSourceTrigger设置为PropertyChanged,因此它应该更新。

任何帮助将不胜感激 :)

1个回答

0

TextBox 的 Text 属性是字符串类型,但您的 Username 属性是一个对象。

考虑将 Username 属性更改为字符串而不是对象。如果您需要它是一个对象,则需要有一个转换器以便绑定正确设置它。

此外,查看您的绑定,我注意到您将其设置为单向。将其更改为双向以确保绑定从源和目标双向更新。


我已将它转换为字符串格式。但还是没有运气:(public static string username; public string Username { get { return username; } set { username = value; } } - Abdulraheem Abid
我已经尝试了所有模式,但仍然没有任何效果。但我会将其保留为TwoWay。 - Abdulraheem Abid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接