avalondock我如何以编程方式绑定Title,IsSelected等属性

时间:2015-05-15 08:43:09

标签: c# wpf avalondock

我正在使用avalondock版本2.我想知道如何以编程方式绑定Title,IsSelected等属性。从LayoutDocument到ViewModel。我想使用SetBinding,但遗憾的是LayoutDocument没有这样的方法。

更新 我知道这种方法,但遗憾的是它不适合我。我为控制Windows做DockingService,而DockingService有一个方法

public void ShowDocumentWindow<TViewModel>() where TViewModel : DocumentItemViewModel
    {
        var viewModel = this.CreateViewModel(typeof(TViewModel));
        var view = this.CreateView(viewModel);

        var documentPane = this.dockingManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

        if (documentPane != null)
        {
            var layoutDocument = new LayoutDocument
            {
                Content = view
            };

            documentPane.Children.Add(layoutDocument);
        }
    }

但我不知道如何绑定属性Title,IsSelected in this method

2 个答案:

答案 0 :(得分:0)

您必须在View中将ViewModel的实例设置为DataContext。之后,您将可以使用例如关于要绑定的属性的Text="{Binding Path=YourProperty}" ..

答案 1 :(得分:0)

从这篇文章 How to: Create a Binding in Code 中,您可以使用 BindingOperations.SetBinding

所以你的代码可以变成这样(以绑定标题为例):

public void ShowDocumentWindow<TViewModel>() where TViewModel : DocumentItemViewModel
{
    var viewModel = this.CreateViewModel(typeof(TViewModel));
    var view = this.CreateView(viewModel);

    var documentPane = this.dockingManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

    if (documentPane != null)
    {
        var layoutDocument = new LayoutDocument
        {
            Content = view
        };
        Binding binding = new Binding("SomeProperty"); //viewModel.SomeProperty
        binding.Source = viewModel;
        BindingOperations.SetBinding(layoutDocument, LayoutDocument.TitleProperty, binding);
        documentPane.Children.Add(layoutDocument);
    }
}