XAML 其他页面上的数据绑定不起作用

e5nqia27  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(136)

我可以绑定MainPage.xaml中的数据,但我不能绑定其他页面。我在这个项目中有一个名为“文档”的模型。
示例:我在MainPage中绑定了FileName

<TextBlock x:Name="NameOfFile" Text="{Binding Document.FilePath}"/>

打开文件时文本显示FileName。
但FileName未显示在另一页上。

<TextBlock x:Name="NameOfFile1" Text="{Binding Document.FilePath}"/>

我想在另一页上显示FileName。我该怎么做?

kcugc4gi

kcugc4gi1#

你可以试试两种方法。

第一个直接将值传递给新页面。

    • 在主页中**
private void Button_Click(object sender, RoutedEventArgs e)
 {
      Frame rootFrame = new Frame();

      Window.Current.Content = rootFrame;

      rootFrame.Navigate(typeof(BlankPage1),document);    
 }
    • 在另一页**
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var param = (Document)e.Parameter; 
    Document.FilePath= param.FilePath;
}

第二种方法是对Document使用singleton模型。

    • 文档视图模型. cs**
public sealed class Document : INotifyPropertyChanged
{
    private static readonly Document instance = new Document("default path");

    public event PropertyChangedEventHandler PropertyChanged;

    public string filePath;
    public int fileSize;

    static Document() { }
    private Document(string value) 
    {
        this.filePath = value;
    }
    public string FilePath
    {
        get { return filePath; }
        set
        {
            filePath = value;
            OnPropertyChanged();
        }

    }
    private void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public static Document Instance { get { return instance; } }
   
}
    • 主页**

一个三个三个一个

    • 空白页1**
<TextBlock  Text="{x:Bind document.FilePath, Mode=OneWay}"></TextBlock>
public sealed partial class BlankPage1 : Page
{
    Document document = Document.Instance;

    public BlankPage1()
    {
        this.InitializeComponent();
           
    }
}

相关问题