【问题标题】:Setting the DataContext to the current code-behind object in XAML将 DataContext 设置为 XAML 中的当前代码隐藏对象
【发布时间】:2017-05-23 22:14:21
【问题描述】:

我正在尝试将我的 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 RelativeSource={RelativeSource Mode=Self}}" 在我的 MainWindow 上有效,但在此 UserControl 上无效。这很奇怪......
  • ScrollViewer 中的 ListBox 有什么意义?
  • 刚刚开始学习。主要使用占位符的东西。我在 ListBox 上看到了 HandlesScrolling 属性。我猜你问是因为 ListBox 已经实现了滚动?
  • 没错,将一个滚动组件放入另一个滚动组件时要小心

标签: c# wpf xaml


【解决方案1】:
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 绑定机制。

【讨论】:

  • 当然就是这么简单...*拍脑袋*。谢谢。在我学习绳索时,字符串列表仅用于测试目的。下一步是自定义树结构,然后实现 INotifyCollectionChanged。
猜你喜欢
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
相关资源
最近更新 更多