Приложение C # WPF сохраняет настройки в UserControl

У меня есть основное приложение, в котором есть граница разных кнопок. Сюда также входит кнопка «Einstellung». При нажатии этой кнопки должно отображаться другое содержимое, чем раньше. Я понял это с помощью UserControl.

Теперь вы можете выполнить настройки в этом пользовательском элементе управления и сохранить их.

введите описание изображения здесь

Это сохранение я сделал в настройках

и с Кодексом

Vorschau.Properties.Settings.Default.BreiteBitmap = Int32.Parse(tbBreiteBitmap.Text);
Vorschau.Properties.Settings.Default.HoeheBitmap = Int32.Parse(tbHoeheBitmap.Text);
Vorschau.Properties.Settings.Default.AnzahlKoordinaten = Int32.Parse(tbAnzahlKoordinaten.Text);

Теперь нажимаю кнопку "Спайхерн". Он мне настройки сохраняет. Теперь я изменяю UserControl, поэтому нажимаю кнопку «Vorschau», и мне отображается новый контент. Если я сейчас снова нажму на «Einstellung», будет ли контент там, в том виде, в каком я его сохранил.

Но возникает проблема. Закрываю приложение и снова открываю. Теперь я нажимаю на кнопку «Einstellung» в текстовых полях, только везде в нем 0.

введите описание изображения здесь

Так быть не должно, но контент должен быть оттуда в прошлом.

Я получаю это содержимое при запуске приложения. См. Фрагмент кода.

 public UCEinstellung()
        {
            InitializeComponent();

            //Lade der Einstellungen
            tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();
        }

И

public MainWindow()
        {
            InitializeComponent();
            MouseDown += Window_MouseDown;

            einstellung.tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            einstellung.tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            einstellung.tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();

        }

К сожалению, это не работает. Надеюсь, ты скажешь мне, в чем ошибка. В другом приложении БЕЗ usercontrol работает, это сохраняет и извлекает правильно.

UCEinstellung

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace Vorschau
{
    /// <summary>
    /// Interaktionslogik für UCEinstellung.xaml
    /// </summary>
    public partial class UCEinstellung : UserControl
    {
        public UCEinstellung()
        {
            InitializeComponent();

            //Lade der Einstellungen
            tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();
        }

        private static Boolean kontrolliereObZahl(String pText)
        {
            int zahl1;
            double zahl2;
            Boolean istZahl;
            if (Int32.TryParse(pText, out zahl1) || Double.TryParse(pText, out zahl2))
            {
                istZahl = true;
            }
            else
            {
                istZahl = false;
            }
            return istZahl;
        }

        private static Boolean textfeldRot(String pBreiteBitmap, String pHoeheBitmap, String pAnzahlKoordinaten)
        {
            Boolean istRot = true;
            if (pBreiteBitmap.Equals("61381638") || pHoeheBitmap.Equals("61381638") || pAnzahlKoordinaten.Equals("61381638"))
            {
                istRot = true;
            }
            else
            {
                istRot = false;
            }
            return istRot;
        }
        private void btSpeichern_Click(object sender, RoutedEventArgs e)
        {

                if (textfeldRot(tbBreiteBitmap.BorderBrush.GetHashCode().ToString(), tbHoeheBitmap.BorderBrush.GetHashCode().ToString(), tbAnzahlKoordinaten.BorderBrush.GetHashCode().ToString()))
                {
                    MessageBox.Show("Leider beinhalten die Eingabefelder falsche Werte.\n\nVersuchen Sie es bitte erneut.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    try
                    {
                        Vorschau.Properties.Settings.Default.BreiteBitmap = Int32.Parse(tbBreiteBitmap.Text);
                        Vorschau.Properties.Settings.Default.HoeheBitmap = Int32.Parse(tbHoeheBitmap.Text);
                        Vorschau.Properties.Settings.Default.AnzahlKoordinaten = Int32.Parse(tbAnzahlKoordinaten.Text);
                        MessageBox.Show("Einstellungen wurden erfolgreich abgespeichert.", "Speicherung erfolgreich", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                    }
                    catch (Exception error)
                    {

                        MessageBox.Show("Unglücklicherweise trat beim Speichervorgang ein Fehler auf.\n\nVersuchen Sie es bitte erneut.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                        Debug.WriteLine("Error - beim Speichervorgang " + error);
                    }
                }            
        }

        private void tbBreiteBitmap_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (kontrolliereObZahl(tbBreiteBitmap.Text) == false)
                {
                    tbBreiteBitmap.BorderBrush = Brushes.Red;
                }
                else
                {
                    tbBreiteBitmap.BorderBrush = Brushes.LightGray;
                }
            }
            catch (Exception error)
            {
                Debug.WriteLine("Error 'tbBreitBitMap'" + error);
            }
        }

        private void tbHoeheBitmap_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (kontrolliereObZahl(tbHoeheBitmap.Text) == false)
                {
                    tbHoeheBitmap.BorderBrush = Brushes.Red;
                }
                else
                {
                    tbHoeheBitmap.BorderBrush = Brushes.LightGray;
                }
            }
            catch (Exception error)
            {
                Debug.WriteLine("Error 'tbHoeheBitmap'" + error);
            }
        }

        private void tbAnzahlKoordinaten_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (kontrolliereObZahl(tbAnzahlKoordinaten.Text) == false)
                {
                    tbAnzahlKoordinaten.BorderBrush = Brushes.Red;
                }
                else
                {
                    tbAnzahlKoordinaten.BorderBrush = Brushes.LightGray;
                }
            }
            catch (Exception error)
            {
                Debug.WriteLine("Error 'tbAnzahlKoordinaten'" + error);
            }
        }
    }
}

<UserControl x:Class="Vorschau.UCEinstellung"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Vorschau"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid Margin="0,0,-326,-161">
        <TextBox x:Name="tbBreiteBitmap" HorizontalAlignment="Left" Height="23" Margin="145,38,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="85" LostFocus="tbBreiteBitmap_LostFocus"/>
        <TextBox x:Name="tbHoeheBitmap" HorizontalAlignment="Left" Height="23" Margin="145,83,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="85" LostFocus="tbHoeheBitmap_LostFocus"/>
        <Label x:Name="label" Content="Breite:" HorizontalAlignment="Left" Margin="10,36,0,0" VerticalAlignment="Top"/>
        <Label x:Name="label_Copy" Content="Höhe:" HorizontalAlignment="Left" Margin="10,77,0,0" VerticalAlignment="Top"/>
        <Label x:Name="label_Copy1" Content="in PX" HorizontalAlignment="Left" Margin="247,35,0,0" VerticalAlignment="Top"/>
        <Label x:Name="label_Copy2" Content="in PX" HorizontalAlignment="Left" Margin="247,77,0,0" VerticalAlignment="Top"/>
        <Label x:Name="label1" Content="einstellbare Größe des Bitmaps" HorizontalAlignment="Left" Margin="10,5,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
        <Label x:Name="label1_Copy" Content="einstellbare Zahl der geenerierten Koordinaten" HorizontalAlignment="Left" Margin="10,172,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
        <Label x:Name="label_Copy3" Content="Anzahl Koordinaten:" HorizontalAlignment="Left" Margin="10,203,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tbAnzahlKoordinaten" HorizontalAlignment="Left" Height="23" Margin="145,203,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="85" LostFocus="tbAnzahlKoordinaten_LostFocus"/>
        <Image x:Name="image" HorizontalAlignment="Left" Height="350" Margin="289,10,0,0" VerticalAlignment="Top" Width="350" Source="img/imageedit_1_9734874017.png" RenderTransformOrigin="0.5,0.5">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform ScaleY="1"/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>
        <Label x:Name="label1_Copy1" Content="Wertebreich des Koordinatensystems" HorizontalAlignment="Left" Margin="323,5,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
        <Canvas HorizontalAlignment="Left" Height="405" Margin="299,23,0,0" VerticalAlignment="Top" Width="3" Background="#FFB8B8B8" RenderTransformOrigin="0.5,0.5">
            <Canvas.RenderTransform>
                <TransformGroup>
                    <ScaleTransform ScaleX="-1"/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </Canvas.RenderTransform>
        </Canvas>
        <Button x:Name="btSpeichern" Content="Speichern" HorizontalAlignment="Left" Margin="30,418,0,0" VerticalAlignment="Top" Width="75" Click="btSpeichern_Click"/>
    </Grid>
</UserControl>

MainWindow

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Vorschau
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        UCEinstellung einstellung = new UCEinstellung();
        UCVorschau vorschau = new UCVorschau();

        public MainWindow()
        {
            InitializeComponent();
            MouseDown += Window_MouseDown;

            einstellung.tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            einstellung.tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            einstellung.tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();

        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                DragMove();
        }

        private void lbClose_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void lbMinimize_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            lbWhereIAm.Content = "Vorschau";
            conCon.Content = vorschau;
        }

        private void btEinstellung_Click(object sender, RoutedEventArgs e)
        {
            lbWhereIAm.Content = "Einstellung";
            einstellung.tbBreiteBitmap.Text = "Test";
            conCon.Content = einstellung;
            einstellung.tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            einstellung.tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            einstellung.tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Vorschau
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        UCEinstellung einstellung = new UCEinstellung();
        UCVorschau vorschau = new UCVorschau();

        public MainWindow()
        {
            InitializeComponent();
            MouseDown += Window_MouseDown;

            einstellung.tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            einstellung.tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            einstellung.tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();

        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                DragMove();
        }

        private void lbClose_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void lbMinimize_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            lbWhereIAm.Content = "Vorschau";
            conCon.Content = vorschau;
        }

        private void btEinstellung_Click(object sender, RoutedEventArgs e)
        {
            lbWhereIAm.Content = "Einstellung";
            einstellung.tbBreiteBitmap.Text = "Test";
            conCon.Content = einstellung;
            einstellung.tbBreiteBitmap.Text = Vorschau.Properties.Settings.Default.BreiteBitmap.ToString();
            einstellung.tbHoeheBitmap.Text = Vorschau.Properties.Settings.Default.HoeheBitmap.ToString();
            einstellung.tbAnzahlKoordinaten.Text = Vorschau.Properties.Settings.Default.AnzahlKoordinaten.ToString();

        }
    }
}

<Window x:Name="windowsForm" x:Class="Vorschau.MainWindow"
        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:local="clr-namespace:Vorschau"
        mc:Ignorable="d"
        Title="Vorschaukomponente" Height="514.583" Width="805.208" FontFamily="Century Gothic" WindowStartupLocation="Manual" BorderThickness="0" ResizeMode="NoResize" WindowStyle="None" Icon="img/coordinates.ico" Background="{x:Null}" AllowsTransparency="True">
    <Window.Resources>

        <Style x:Key="border_res" TargetType="{x:Type Border}">
            <Setter Property="Background" Value="#3A3A3B" />
            <Setter Property="CornerRadius" Value="10" />
        </Style>
    </Window.Resources>

    <Border Style="{StaticResource border_res}">
        <Grid>
            <Canvas HorizontalAlignment="Left" Height="60" VerticalAlignment="Top" Width="185" Background="#FFE57E31">
                <Canvas Height="64" Canvas.Top="451" Width="185" Background="#FF2C373F">
                    <Label x:Name="lbCopyright" Content="©  Name 2017" Canvas.Left="10" Canvas.Top="29" Width="121" Foreground="#FF1B1D1F"/>
                </Canvas>
                <Canvas Height="391" Canvas.Top="60" Width="185" Background="#FF37424A">
                    <Button x:Name="btVorschau" Content="Vorschau" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="185" Height="50" Foreground="LightGray" FontSize="16"
                HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Click="Button_Click">
                        <Button.Style>
                            <Style TargetType="{x:Type Button}">
                                <Setter Property="Background" Value="#FF37424A"/>
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="{x:Type Button}">
                                            <Border Background="{TemplateBinding Background}">
                                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                            </Border>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Background" Value="#FF303B43"/>
                                        <Setter Property="Foreground" Value="Red"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>
                    <Button x:Name="btEinstellung" Content="Einstellung" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="185" Height="50" Foreground="LightGray" FontSize="16"
                        HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Canvas.Top="50" Click="btEinstellung_Click">
                        <Button.Style>
                            <Style TargetType="{x:Type Button}">
                                <Setter Property="Background" Value="#FF37424A"/>
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="{x:Type Button}">
                                            <Border Background="{TemplateBinding Background}">
                                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                            </Border>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Background" Value="#FF303B43"/>
                                        <Setter Property="Foreground" Value="Red"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>
                </Canvas>
                <Canvas Height="60" Canvas.Left="185" Width="618" Background="#FFEEE9ED">
                    <Label x:Name="lbClose" Content="X" Canvas.Left="578" FontSize="20" MouseDoubleClick="lbClose_MouseDoubleClick"/>
                    <Label x:Name="lbMinimize" Content="-" Canvas.Left="556" FontSize="22" Canvas.Top="-2" MouseDoubleClick="lbMinimize_MouseDoubleClick"/>
                    <Label x:Name="lbWhereIAm" Content="Label" Canvas.Left="10" Canvas.Top="15" Width="162" FontSize="20"/>
                </Canvas>
                <Canvas x:Name="canvasContent" Height="455" Canvas.Left="185" Canvas.Top="60" Width="618" Background="#FFD1CFD0"/>
                <Image x:Name="image" Height="38" Canvas.Left="10" Canvas.Top="10" Width="38" Source="img/coordinatesWhite.png"/>
                <Label x:Name="lbLogoname" Content="Vorschaukomponente" Canvas.Left="37" Canvas.Top="10" Width="143" FontWeight="Bold" Foreground="White"/>
            </Canvas>
            <ContentControl x:Name="conCon" Content="ContentControl" Canvas.Left="86" Canvas.Top="31" Margin="185,60,0,0" Foreground="#FF002EFF"/>
        </Grid>
    </Border>
</Window>

person Community    schedule 24.02.2017    source источник
comment
Определенно вы должны прочитать это.   -  person Hamlet Hakobyan    schedule 24.02.2017


Ответы (1)


Похоже, вы просто назначаете свойства, а не сохраняете их. Вам нужно вызвать метод Save

Vorschau.Properties.Settings.Default.Save();

После сохранения вы сможете найти файл в папке %userprofile%\appdata\local. Подробнее см. здесь.

Чтобы это работало, область действия должна быть «Пользователь».

person HebeleHododo    schedule 24.02.2017
comment
Это то, что я упустил. Это сработало. Большое тебе спасибо! - person ; 24.02.2017