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

2024-01-04

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

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

    public OHMDataPage ()
    {
        InitializeComponent();

        DataContext = this;
    }
}
<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">

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

</UserControl>

但是我怎样才能纯粹从 XAML 端和 UserControl 级别执行此操作呢?如果我这样做(并删除DataContext = this;从代码隐藏):

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

    <ScrollViewer
        DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">
        <ListBox ItemsSource="{Binding Stuff}" />
    </ScrollViewer>

</UserControl>

我真的很想了解如何在 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" };
}

如果您使用字符串列表,请考虑使用ObservableCollection反而。当添加或删除项目时,这将通知 WPF 绑定机制。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 DataContext 设置为 XAML 中的当前代码隐藏对象 的相关文章

随机推荐