在代码后台定义绑定对象

94

我有一些在代码后端实例化的对象,例如,XAML被称为window.xaml,位于window.xaml.cs中。

protected Dictionary<string, myClass> myDictionary;

我如何使用XAML标记仅将此对象绑定到例如列表视图?

更新:

(这正是我在测试代码中拥有的内容):

<Window x:Class="QuizBee.Host.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="{Binding windowname}" Height="300" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
    </Grid>
</Window>

在代码后台

public partial class Window1 : Window
{
    public const string windowname = "ABCDEFG";

    public Window1()
    {
        InitializeComponent();
    }
}

假设标题应该变成 "ABCDEFG",但最终没有显示任何内容。


1
有趣的是,如果我更改窗口属性分配的顺序,它就无法工作。如果我先设置“Title”属性,然后是“DataContext”属性,绑定就不会发生。有人能解释一下吗?<Window x:Class="INotifyPropertyTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local ="clr-namespace:INotifyPropertyTest" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource self}}" Title="{Binding WindowName}" > - Ramesh
11个回答

0

这是我绑定到代码后面的方式(请参见属性DataTemplateSelector

public partial class MainWindow : Window
{
  public MainWindow()
  {
    this.DataTemplateSelector = new MyDataTemplateSelector();

    InitializeComponent();

    // ... more initializations ...
  }

  public DataTemplateSelector DataTemplateSelector { get; }

  // ... more code stuff ...
}

在XAML中,可以通过RelativeSource引用祖先元素直到包含Window,因此我在我的Window类中,通过Path声明使用该属性:

<GridViewColumn Header="Value(s)"
                CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>

在调用InitializeComponent之前设置属性DataTemplateSelector取决于缺少IPropertyChanged的实现或使用具有DependencyProperty的实现,因此在更改属性DataTemplateSelector时不会进行通信。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接