c# - 以编程方式在加载的松散 xaml 文件中的控件上设置文本

标签 c# wpf xaml xamlreader

我想在加载的松散 xaml 文件中定义的文本框中设置文本。文本框是应用程序的一部分。

StackPanel LooseRoot;

        if (fTeleFound == true)
        {
            try
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(sXamlFileName, System.IO.FileMode.Open))
                {
                    LooseRoot = (StackPanel)System.Windows.Markup.XamlReader.Load(fs);
                }
                this.DetailsViewFrame.Children.Add(LooseRoot);
            }
            catch (ArgumentException ex)
            {
                // TBD Error xamlfile
                return;
            }


            // set Elements
            //foreach (TextBox textBox in LooseRoot.Children as TextBox) // does not work ?
            //{
                //

            //}
        }

xaml文件是这样的:

<StackPanel Margin="10" Orientation="Vertical"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

<StackPanel Orientation="Horizontal">
    <Label Margin="5,5,0,5">CRCDB=</Label>
    <TextBox Margin="0,5,5,5" Name="DetailsviewTB1" Height="20"/>

    <Label Margin="10,5,0,5">Infonummer=</Label>
    <TextBox Margin="0,5,5,5" Name="DetailsviewTB2" Height="20"/>

    <Label Margin="10,5,0,5">Daten=</Label>
    <TextBox Margin="0,5,5,5" Name="DetailsviewTB3" Height="20"/>
</StackPanel>

这是用于必须在不编译新应用程序的情况下进行自定义的详细信息 View 。编译时不知道松散的 xaml 文件的数量及其名称。

如何动态设置文本框上的文本?我有一个额外的 xml 文件,可以指定哪些数据来自哪个 TextBox。

最佳答案

你能bind他们?如果是这样,我肯定会推荐这样做,那么你只需要设置 DataContext到包含值的对象。

否则你可以胡闹LogicalVisualTreeHelpers ,递归地寻找具有正确名称的 TextBox。你也可以试试 FindName在包含您的 StackPanel 的一些 FrameworkElement 上。

关于c# - 以编程方式在加载的松散 xaml 文件中的控件上设置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11804401/

相关文章:

C# - 如何使用制表符正确缩进字符串数据?

c# - 如何使 DataTemplate 响应 WPF 中的双击?

c# - 如何在 C#/WPF/XAML 中将整个对象而不只是一个属性绑定(bind)到组合框列表的控件?

wpf - 表达式混合合并路径函数

wpf - 从 StoryBoard 访问 Grid.Columnspan

xaml - 未检测到已安装的组件。无法解析 TargetName HighContrastBorder - UWP Windows 10

wpf - 如何正确设置精美的垂直 ProgressBar 样式?

c# - mysql datareader 找不到行 c#

c# - QueryAsyc 和使用 lambda 查询表有什么区别?

c# - 无法从 'method group' 转换为 Action