0

Есть один TextBox для ввода текста и дальнейшего его сжатия

<TextBox Grid.Row="0" Grid.ColumnSpan="4" AcceptsReturn="True"
                         SpellCheck.IsEnabled="True" Language="ru-ru"
                         VerticalScrollBarVisibility ="Auto" Text="{Binding Path=MainText, UpdateSourceTrigger=PropertyChanged}"
                         FontSize="14" Margin="5,5,5,5" Grid.RowSpan="1"/>

При попытке изменить содержимое через функции Открыть после которой ты выбираешь файл с текстом содержимое TextBox не меняется.

Вот само свойство

    private string _MainText = "empty";
public string MainText
{
    get =&gt; _MainText;
    set =&gt; Set(ref _MainText, value);
}

Метод Set из классаPropertyChangeding

 public class PropertyChangeding : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string prop = "") 
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
protected virtual bool Set&lt;T&gt;(ref T fules, T value, [CallerMemberName] string prop = &quot;&quot;)
{
    if (object.Equals(fules, value)) return false;
    fules = value;
    OnPropertyChanged(prop);
    return true;
}

}

Команда для открытия

 public ICommand OpenNewFileCommand { get; }
private bool CanOpenNewFileCommandExecute(object p) =&gt; true;
private void OnOpenNewFileCommandExecited(object p)
{
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = &quot;Text documents (*.txt)|*.txt|All files (*.*)|*.*&quot;;
    dialog.FilterIndex = 2;

    Nullable&lt;bool&gt; result = dialog.ShowDialog();

    if (result == true)
    {
        // Open document
        string text = File.ReadAllText(dialog.FileName);
        MainText = text;
    }

}

Весь XAML код

<Window x:Class="Course_work_IT.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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    xmlns:view="clr-namespace:Course_work_IT.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="900">

<Window.DataContext> <view:BaseVeiwModel/> </Window.DataContext>

<Window.InputBindings> <KeyBinding Modifiers="Ctrl" Key="X" Command="{Binding CloseApplicationCommand}"/> </Window.InputBindings>

<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <materialDesign:BundledTheme BaseTheme="Light" PrimaryColor="Purple" SecondaryColor="Lime" /> <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources>

<DockPanel> <Menu DockPanel.Dock="Top" FontSize="13" Height="38" VerticalAlignment="Center" > <Menu.DataContext> <view:PersonTextViewModel/> </Menu.DataContext> <MenuItem Header="File"> <MenuItem Header="Открыть" Command="{Binding Path=OpenNewFileCommand}"/> <MenuItem Header="Exit" Command="{Binding CloseApplicationCommand}"/> <MenuItem Header="Run" Command="{Binding Path=ChangeProgressBarCommand}"/> </MenuItem> <MenuItem Header="About"> <MenuItem Header="Info"/> </MenuItem> <MenuItem Header="{Binding Path=MainText, UpdateSourceTrigger=PropertyChanged}"/> <TextBox Text="{Binding Path=MainText, UpdateSourceTrigger=PropertyChanged}"/>

    &lt;MenuItem Header=&quot;Назад&quot; Command=&quot;{Binding Path=ChangeSelectedItemCommand}&quot; CommandParameter=&quot;-1&quot;/&gt;
    &lt;MenuItem Header=&quot;Вперед&quot; Command=&quot;{Binding Path=ChangeSelectedItemCommand}&quot; CommandParameter=&quot;+1&quot;/&gt;
&lt;/Menu&gt;
&lt;StatusBar DockPanel.Dock=&quot;Bottom&quot;&gt;
    &lt;StatusBarItem&gt;
        &lt;TextBlock Text=&quot;{Binding Path=ProcessProgressbar, UpdateSourceTrigger=LostFocus}&quot; MinHeight=&quot;15&quot; MinWidth=&quot;50&quot;/&gt;
    &lt;/StatusBarItem&gt;
    &lt;StatusBarItem&gt;
        &lt;ProgressBar Width=&quot;120&quot; Height=&quot;14&quot; Value=&quot;{Binding Path=ProgressBarValue, UpdateSourceTrigger=PropertyChanged, Mode = OneWay}&quot;&gt;
        &lt;/ProgressBar&gt;
    &lt;/StatusBarItem&gt;
&lt;/StatusBar&gt;
&lt;TabControl SelectedIndex=&quot;{Binding Path=SelectedItem}&quot; FontFamily=&quot;Lucida Sans&quot;&gt;

    &lt;TabItem Header=&quot;Кодирование&quot;&gt;

        &lt;Grid HorizontalAlignment=&quot;Stretch&quot;&gt;

            &lt;Grid.DataContext&gt;
                &lt;view:PersonTextViewModel/&gt;
            &lt;/Grid.DataContext&gt;

            &lt;Grid.ColumnDefinitions&gt;
                &lt;ColumnDefinition Width=&quot;381*&quot;/&gt;
                &lt;ColumnDefinition Width=&quot;259*&quot;/&gt;
                &lt;ColumnDefinition Width=&quot;56*&quot;/&gt;
                &lt;ColumnDefinition Width=&quot;104*&quot;/&gt;
            &lt;/Grid.ColumnDefinitions&gt;

            &lt;Grid.RowDefinitions&gt;
                &lt;RowDefinition Height=&quot;0.825*&quot;/&gt;
                &lt;RowDefinition Height=&quot;0.175*&quot;/&gt;
            &lt;/Grid.RowDefinitions&gt;

            &lt;TextBox Grid.Row=&quot;0&quot; Grid.ColumnSpan=&quot;4&quot;  Grid.RowSpan=&quot;1&quot; Text=&quot;{Binding Path=MainText}&quot;/&gt;

            &lt;Grid Grid.Row=&quot;1&quot; Grid.Column=&quot;0&quot; Grid.ColumnSpan=&quot;2&quot;&gt;

                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
                &lt;/Grid.ColumnDefinitions&gt;

                &lt;TextBlock
                    Text=&quot;Алгоритм сжатия :&quot;
                    Grid.Column=&quot;0&quot; 
                    VerticalAlignment=&quot;Center&quot;
                    HorizontalAlignment=&quot;Left&quot;
                    Margin=&quot;10, 0, 0, 0&quot;/&gt;

                &lt;ComboBox Grid.Column=&quot;0&quot; 
                          HorizontalAlignment=&quot;Center&quot;
                          Margin=&quot;90, 0, 0, 0&quot;
                          SelectedItem=&quot;{Binding Path=Algorithm}&quot;
                          ItemsSource=&quot;{Binding Path=_algorithms}&quot;
                          Width=&quot;50&quot;&gt;
                &lt;/ComboBox&gt;

                &lt;StackPanel Grid.Column=&quot;1&quot; Orientation=&quot;Horizontal&quot;&gt;

                    &lt;TextBlock 
                        HorizontalAlignment=&quot;Left&quot;
                        Text=&quot;Название файла :&quot;
                        Grid.Column=&quot;1&quot; 
                        VerticalAlignment=&quot;Center&quot;
                        Margin=&quot;10, 0, 20, 0&quot;/&gt;

                    &lt;TextBox
                        Text=&quot;{Binding Path=FileName}&quot;
                        Grid.Column=&quot;1&quot;
                        VerticalAlignment=&quot;Center&quot;
                        HorizontalAlignment=&quot;Right&quot;
                        Margin=&quot;0, 0, 0, 0&quot;/&gt;
                &lt;/StackPanel&gt;

                &lt;TextBlock

                    Text=&quot;Степень сжатия :&quot;
                    Grid.Column=&quot;2&quot; 
                    VerticalAlignment=&quot;Center&quot;
                    HorizontalAlignment=&quot;Left&quot;
                    Margin=&quot;10, 0, 0, 0&quot;/&gt;

                &lt;ComboBox Grid.Column=&quot;2&quot; 
                          HorizontalAlignment=&quot;Center&quot;
                          Margin=&quot;110, 0, 0, 0&quot;
                          SelectedItem=&quot;{Binding Path=Comprassion}&quot;
                          ItemsSource=&quot;{Binding Path=_comprassions}&quot;
                          Width=&quot;100&quot;&gt;
                &lt;/ComboBox&gt;
            &lt;/Grid&gt;
            &lt;StackPanel Grid.Row=&quot;1&quot; Grid.Column=&quot;2&quot; Grid.ColumnSpan=&quot;2&quot; Orientation=&quot;Vertical&quot;&gt;
                &lt;Label Content=&quot;Текст должен быть больше 200 символов&quot; Margin=&quot;0,0,0,0&quot; FontSize=&quot;6&quot; HorizontalContentAlignment=&quot;Center&quot; /&gt;
                &lt;Button Command=&quot;{Binding Path=SaveNewFileCommand}&quot; CommandParameter=&quot;true&quot;
                HorizontalAlignment=&quot;Left&quot; Margin=&quot;34,0,0,13&quot; 
                Cursor=&quot;Hand&quot; FontSize=&quot;20&quot;&gt;
                    &lt;TextBlock Text=&quot;сжать&quot; FontSize=&quot;20&quot; Margin=&quot;0,-4,0,0&quot; FontFamily=&quot;Bodoni MT Black&quot;/&gt;
                &lt;/Button&gt;
            &lt;/StackPanel&gt;
        &lt;/Grid&gt;
    &lt;/TabItem&gt;

    &lt;TabItem Header=&quot;Декодирование&quot;&gt;
        &lt;Grid&gt;&lt;/Grid&gt;
    &lt;/TabItem&gt;

&lt;/TabControl&gt;

</DockPanel>

  • Если команда и свойство находятся в одном классе VM, то подозреваю, что используются разные экземпляры VM для DataContext. Покажите, каким образом устанавливаете DataContext для окна или UC...? – alex6327 Oct 10 '22 at 09:18
  • После некоторых тестов, а именно я создал в Menu поля, которые я забиндил к свойству MainText (то же свойство и у Textbox), эти поля взаимосвязанны и прекрасно текст в них меняется, но в самом TextBox, почему то вначале текст привязывается, а после он не обновляется –  Oct 10 '22 at 09:35
  • <Window.DataContext> - плохо, забудьте про это. Это кстати наверно и ваша проблема с обновление, ибо у вас в XAML задан один экземпляр VM класса, а в коде небось пишете var vm = new BaseVeiwModel(); vm.MainText = "....";, что означает "Создать новый экземпляр класса и в нем поменять значение свойства". Другими словами, у вас два объекта BaseVeiwModel со своими значениями, где один привязан к UI, а другой используется в коде. – EvgeniyZ Oct 10 '22 at 14:51

0 Answers0