如何在Silverlight中全局更新文本块字符串?

时间:2011-03-03 21:38:21

标签: silverlight xaml silverlight-4.0

我需要根据使用OpenDialog Window选择的文件名更新childWindow中的文本块。由于我没有从childWindow运行OpenDialog,因此无法将该值传递给ChildWindow中的texblock。我想知道是否有人可以提供帮助。由于我遇到了这个问题,我想知道是否可以在ChildWindow中使用OpenDialog?谢谢你的任何想法!

ChildWindow xaml:

<sdk:ChildWindow 
x:Class="AddPackages_ChildWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"   
xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
AutomationProperties.AutomationId="AddPackages_ChildWindow">

<Grid x:Name="AddPackages_ChildWindow_LayoutRoot" AutomationProperties.AutomationId="AddPackages_ChildWindow_LayoutRoot" Style="{StaticResource AVV_GridStyle}">
    <TextBlock x:Name="txtUpdate_Package" AutomationProperties.AutomationId="txtUpdate_Package" Text="FileName" />  </Grid>

下面是打开DialogBox并传递所选文件名的代码:

private void Package_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        AddPackage_ChildWindow ap = new AddPackage_ChildWindow();
        ap.Show();

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "App-V Packages (*.sprj)|*.sprj|App-V Packages (*.sprj)|*.sprj";
        openFileDialog1.FilterIndex = 1;

        openFileDialog1.Multiselect = true;

        bool? userClickedOK = openFileDialog1.ShowDialog();

        if (userClickedOK == true)
        {
            //passing the file name string
            txtUpdate_Package.Text = openFileDialog1.File.Name;
            System.IO.Stream fileStream = openFileDialog1.File.OpenRead();

            using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
            {
                // Read the first line from the file and write it the textbox.
                // txtUpdate_Package.Text = reader.ReadLine();
            }
            fileStream.Close();
        }
    }

2 个答案:

答案 0 :(得分:1)

您可以在ChildWindow类上公开SetText方法,如下所示:

public void SetText(string text) {
    this.txtUpdate_Package.Text = text;
}

然后你会从你的Package_Click方法中调用它:

ap.SetText(reader.ReadLine());

答案 1 :(得分:1)

如果您不太关心OO纯粹主义者的想法,您可以在代码中更改此行: -

txtUpdate_Package.Text = openFileDialog1.File.Name;

到此: -

ap.txtUpdate_Package.Text = openFileDialog1.File.Name;

这是因为为您的子窗口Xaml创建的自动生成的类文件将具有一个名为TextBlock的字段txtUpdate_Package,可以访问内部,即

internal TextBlock txUpdate_Package;

此字段是在ChildWindow的InitializeComponent方法中指定的,该方法被称为其构造函数的一部分。

但是,我更愿意创建一个用于处理此问题的公共属性,而不是编写依赖于应该被视为私有内部结构的代码。将此属性添加到子窗口后面的代码中。

public string Text
{
     get { return txtUpdate_Package.Text; }
     set { txtUpdate_Package.Text = value; }
}