将子用户控件绑定到类属性

时间:2015-10-05 15:26:35

标签: wpf

我有一个名为BookControl的usercotrol。我将usercontrol作为子项添加到名为MainWindow的窗口中。我想将子控件绑定到MainViewModel中的属性。

我使用的是mvvm灯。 感谢。

这是我的代码:

主窗口

    <Window 
     DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
 <Controls:BookControl DataContext="{Binding Path=bookviewmodel}" ></Controls:BookControl>

MainViewModel

    public BookViewModel bookviewmodel { get; set; }
  public MainViewModel()
    {
        bookviewmodel = new BookViewModel();

    }

BookViewModel

  public BookModel Book { get; set; }

    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>

    public BookViewModel()
    {
        Book = new BookModel{Title = "A Book", Author = "Some Author", Description = "Its a really good book!"};
    }

BookControl

<UserControl>
<Grid>
 <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Title}"/>
        <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Author}"/>
        <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Description}"/>
        <Button Grid.Row="3" Command="{Binding SaveCommand}" Content="Save" />
</Grid>
</UserControl>

2 个答案:

答案 0 :(得分:0)

尝试创建ViewModel属性,如下所示

private BookViewModel _BookViewModel ; 
public BookViewModel BookViewModel 
 { 
   get { return _BookViewModel ; } 
   set { 
          _BookViewModel = value; 
          NotifyPropertyChanged(); 
       } 
 }

答案 1 :(得分:0)

使您的属性成为依赖项属性或使用INotifyPropertyChanged。