You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不显示Window的情况下使WPF XAML绑定生效?

问题:无Window场景下让XAML绑定在Window Show()前生效

我希望用XAML构建工作流以分离设计与功能,示例如下:

<Command x:Class="MyCommand">
  <Step1 Name="">
     <Step2 />
  </Step1>
</Command>

这种方式可行,但需要获取更新值时只能通过事件实现:

<Command x:Class="MyCommand">
  <Step1  GetName="OnGetName">
     <Step2 />
  </Step1>
</Command>
void OnGetName(out string name){name = "xxx";}

我认为WPF的Binding机制更适合需求,但因无Window且类未继承Control,无法使用,即使继承DependencyObject也不行。我想知道是否有类似方法实现Binding。


后续更新:实际需求是在无Window场景下使用XAML绑定。最初不想继承Control或FrameworkElement,发现不可行后改为继承FrameworkElement,此时代码绑定可生效,但XAML绑定不行。

代码示例

Command类(继承FrameworkElement)

public class Command : FrameworkElement
{
       public static readonly DependencyProperty Test1Property = DependencyProperty.Register(
            nameof(Test1), typeof(string), typeof(UserControl1), new PropertyMetadata(default(string)));

        public string Test1
        {
            get { return (string)GetValue(Test1Property); }
            set { SetValue(Test1Property, value); }
        }

        public static readonly DependencyProperty Test2Property = DependencyProperty.Register(
            nameof(Test2), typeof(string), typeof(UserControl1), new PropertyMetadata(default(string)));

        public string Test2
        {
            get { return (string)GetValue(Test2Property); }
            set { SetValue(Test2Property, value); }
        }
}

MainWindow的XAML

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d" x:Name="Main"
        DataContext="{x:Reference Main}"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:UserControl1 x:Name="Control" Test1="{Binding TestStr, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></local:UserControl1>
    </Grid>
</Window>

后台代码初始化Test2绑定

public MainWindow()
{
    InitializeComponent();
    var binding = new Binding("TestStr")
    {
        Source = this,
    };
    BindingOperations.SetBinding(Control, UserControl1.Test2Property, binding);

    TestStr = "XXS";

    MessageBox.Show($"ONLoad: Test1: {Control.Test1}, Test2: {Control.Test2}");
}

当前现象

当实例化MainWindow但不调用Show()时,MessageBox显示:

Test1:, Test2:XXS

我想寻求一种方法,让XAML中定义的绑定在Window Show()前生效。


内容的提问来源于stack exchange,提问作者halong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:20:16