0

I am working on WPF project. I have created a user control name as "CanLogPaneView". this user control contains a Text box called "txt_CanLog". I have bind this Text box as mentioned below:

<UserControl x:Class="CANCONTROL.CanLogPaneView"
             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:CANCONTROL"
             xmlns:ViewModels="clr-namespace:CANCONTROL.ViewModels;assembly=CANCONTROL.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="MainWindowViewModel" DataType="{x:Type ViewModels:MainWindowViewModel}">
        </DataTemplate>
    </UserControl.Resources>
    <DockPanel>
        **<TextBox x:Name="txt_CanLog" Text="{Binding Text, Source={StaticResource MainWindowViewModel}}" >**

        </TextBox>
    </DockPanel>
</UserControl>

So I have bind the text box with mainwindow property Text. My main window have a view model. there I defined the property Text as mentioned below:

public string text = string.Empty;
public string Text
        {
            get
            {
                return text;
            }

            set
            {
                text = text + value;
            }
        }

in Main window code: MainWindow.xaml.cs I am adding text like this.ViewModel.Text = "\n\nAPPLICATION CONFIGURATION\r\n";

What I want is through mainwindow.xaml.cs code I want to print some data in CanLogPaneView.xaml's textBox

Nirali
  • 33
  • 3
Nikhil
  • 1
  • 2

1 Answers1

0

Your MainWindowViewModel should be binded to your Usercontrol's DataContext instead. Also, implement INotifyPropertyChanged in your MainWindowViewModel and RaisePropertyChange at your "Text" setter

Something like the following

<Window x:Class="WpfTestProj.MainWindow"
    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"
    mc:Ignorable="d" 
    xmlns:local="clr-namespace:WpfTestProj"
    Title="MainWindow" Height="350" Width="525"
    d:DataContext="{d:DesignInstance Type=local:MainViewModel, IsDesignTimeCreatable=False}">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>

    <TextBox Text="{Binding Text}" />
</Grid>

public class MainViewModel : ViewModelBase
{
    private string _text;

    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged();
        }
    }
}
cscmh99
  • 2,701
  • 2
  • 15
  • 18