C# 将DataContext设置为XAML中的当前代码隐藏对象

C# 将DataContext设置为XAML中的当前代码隐藏对象,c#,wpf,xaml,C#,Wpf,Xaml,我试图将UserControl的DataContext设置为UserControl的代码隐藏类。从代码背后来说,这真的很容易做到: public partial class OHMDataPage : UserControl { public StringList Stuff { get; set; } public OHMDataPage () { InitializeComponent(); DataContext = this;

我试图将UserControl的DataContext设置为UserControl的代码隐藏类。从代码背后来说,这真的很容易做到:

public partial class OHMDataPage : UserControl
{
    public StringList Stuff { get; set; }

    public OHMDataPage ()
    {
        InitializeComponent();

        DataContext = this;
    }
}
我真的很想了解如何在UserControl本身上实现这一点。我希望这能奏效:

<UserControl 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"
    x:Class="LCDHardwareMonitor.Pages.OHMDataPage"
    DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">

    <ScrollViewer>
        <ListBox ItemsSource="{Binding Stuff}" />
    </ScrollViewer>

</UserControl>

但事实并非如此

DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
应该有用

但是如果在调用
InitializeComponent()
之前未设置属性,则WPF绑定机制不会知道属性的值已更改

给你一个快速的想法:

// the binding should work
public StringList Stuff { get; set; }
public Constructor()
{
    Stuff = new StringList { "blah", "blah", "foo", "bar" };
    InitializeComponent();
}

// the binding won't work
public StringList Stuff { get; set; }
public Constructor()
{
    InitializeComponent();
    Stuff = new StringList { "blah", "blah", "foo", "bar" };
}

如果使用字符串列表,请考虑使用<代码> VistabeCelpEng/<代码>。当添加或删除项时,这将通知WPF绑定机制。

Hmm,如果在我的主窗口上,而不是在此用户控件上,则似乎
DataContext=“{binding RelativeSource={RelativeSource Mode=Self}}”
有效。这很奇怪…ScrollViewer中的列表框有什么意义?只是学习一些技巧而已。主要使用占位符。我在ListBox上看到一个HandleScrolling属性。我猜你会问,因为ListBox已经实现了滚动?确切地说,在将一个滚动组件放入另一个滚动组件时要小心,当然很简单…*头拍*。谢谢字符串列表只是为了在我学习诀窍时进行测试。下一步是定制树结构,然后实现INotifyCollectionChanged。
DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
// the binding should work
public StringList Stuff { get; set; }
public Constructor()
{
    Stuff = new StringList { "blah", "blah", "foo", "bar" };
    InitializeComponent();
}

// the binding won't work
public StringList Stuff { get; set; }
public Constructor()
{
    InitializeComponent();
    Stuff = new StringList { "blah", "blah", "foo", "bar" };
}