简体   繁体   English

加载 XAML 并正确显示

[英]Loading XAML and displaying it properly

I am able to save the Xaml data and then load it again however it doesnt display as I would like it too, this is what it looks like before loading saved data Before loading saved data However after loading all of the buttons disappear After loading I would like to keep the buttons where they are and only load the saved data into its allocated space.我能够保存 Xaml 数据,然后再次加载它,但是它也没有像我想要的那样显示,这是加载保存的数据之前的样子 加载保存的数据之前但是加载后所有按钮都消失了加载后我会喜欢将按钮保留在原处,仅将保存的数据加载到其分配的空间中。 Below is the code any help would be great thanks.以下是任何帮助的代码,非常感谢。

public MainWindow()
{
    InitializeComponent();
}

// button and code to save canvas
public void Button_Click(object sender, RoutedEventArgs e)
{
    string savedCanvas = XamlWriter.Save(cnv);
    File.WriteAllText("canvas.xaml", savedCanvas);
}

// button and code for loading canvas
void Button_Click_1(object sender, RoutedEventArgs e) 
{
    var savedCanvas = File.ReadAllText("canvas.xaml");
    StringReader stringReader = new StringReader(savedCanvas);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    Canvas readerLoadCanvas = (Canvas)XamlReader.Load(xmlReader);
    Content = readerLoadCanvas;
}

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    Block b = new Block();
    hor.Children.Add(b);
}

welcome to SO, From the code that you've provided: the culprit is this line:欢迎来到 SO,根据您提供的代码:罪魁祸首是这一行:

    Content = readerLoadCanvas;

What you are doing here is replacing your MainWindow's entire "Content" with the canvas.xaml code, therefore it will replace all of your buttons along with the original canvas.您在这里所做的是用 canvas.xaml 代码替换 MainWindow 的整个“内容”,因此它将替换您的所有按钮以及原始 canvas。 Because I can't see your xaml code (not posted yet), I can't tell what container your Canvas resides in (ie Grid, StackPanel, etc.).因为我看不到您的 xaml 代码(尚未发布),所以我不知道您的 Canvas 位于哪个容器中(即 Grid、StackPanel 等)。

But if I were to assume that you put your Canvas inside of a Grid, for example, then I can give you an answer.但是,例如,如果我假设您将 Canvas 放在 Grid 中,那么我可以给您一个答案。 Example:例子:

    <Grid x:Name="mainGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <StackPanel x:Name="PanelOfButtons">
            <Button Content="Load" .../>
            <Button Content="Save" .../>
        </StackPanel>
        <Canvas x:Name="cnv" Grid.Column="1" Background="Green">

The answer would be to replace the offending line with this to replace the canvas with your new canvas:答案是用这个替换有问题的行,用你的新 canvas 替换 canvas:

    // Remove the original canvas
    mainGrid.Children.Remove(cnv);
    // Add the new canvas
    mainGrid.Children.Add(readerLoadCanvas);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM