2015-10-08 38 views
0

我正在WPF项目上工作。我已经创建了一个用户控件名称“CanLogPaneView”。此用户控件包含名为“txt_CanLog”的文本框。通过主窗口文本绑定用户控件的文本框

<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> 

所以我已经绑定主窗口属性Text文本框: 我已经下文提到这个文本框绑定。我的主窗口有一个视图模型。还有我所定义的属性文本作为下面提到:在主窗口代码

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

      set 
      { 
       text = text + value; 
      } 
     } 

:MainWindow.xaml.cs我添加文本等 this.ViewModel.Text = “\ n \ nAPPLICATION CONFIGURATION \ r \ n” 个;

我想在CanLogPaneView.xaml的textBox中

回答

0

你MainWindowViewModel应该被绑定到你的用户控件的DataContext的,而不是打印一些数据我要的是通过mainwindow.xaml.cs代码。 此外,在您的MainWindowViewModel和RaisePropertyChange执行INotifyPropertyChanged在你的 “文本” 二传手

像下面

<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(); 
     } 
    } 
}