Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使绑定在不运行应用程序的情况下工作 静态类程序 { [状态线程] 静态void Main() { var win=新的主窗口(); var vm=new ViewModel(); win.DataContext=vm; vm.Test=“Testing”; //var app=新应用程序(); //应用程序运行(win); var text=win.TextBox.text; } 公共类视图模型 { 公共字符串测试{get;set;} }_C#_Wpf_Data Binding_.net 4.5 - Fatal编程技术网

C# 使绑定在不运行应用程序的情况下工作 静态类程序 { [状态线程] 静态void Main() { var win=新的主窗口(); var vm=new ViewModel(); win.DataContext=vm; vm.Test=“Testing”; //var app=新应用程序(); //应用程序运行(win); var text=win.TextBox.text; } 公共类视图模型 { 公共字符串测试{get;set;} }

C# 使绑定在不运行应用程序的情况下工作 静态类程序 { [状态线程] 静态void Main() { var win=新的主窗口(); var vm=new ViewModel(); win.DataContext=vm; vm.Test=“Testing”; //var app=新应用程序(); //应用程序运行(win); var text=win.TextBox.text; } 公共类视图模型 { 公共字符串测试{get;set;} },c#,wpf,data-binding,.net-4.5,C#,Wpf,Data Binding,.net 4.5,如果我按原样运行应用程序,变量text的值将是一个空字符串。如果我取消注释将窗口作为WPF应用程序运行的两行,它将是“测试”,这意味着文本框与classViewModel上属性Test的绑定仅在我“运行”应用程序时才起作用 有什么方法可以使绑定在不实际运行应用程序的情况下工作吗?如果在指定了源代码的情况下手动设置依赖对象的绑定(使用绑定操作。SetBinding),则即使应用程序未运行,绑定也可以正常工作 因此在这种情况下,我认为问题在于窗口尚未加载,因此可视化树尚未准备就绪,因此DataCon

如果我按原样运行应用程序,变量
text
的值将是一个空字符串。如果我取消注释将窗口作为WPF应用程序运行的两行,它将是“测试”,这意味着文本框与class
ViewModel
上属性
Test
的绑定仅在我“运行”应用程序时才起作用


有什么方法可以使绑定在不实际运行应用程序的情况下工作吗?

如果在指定了
源代码的情况下手动设置
依赖对象的绑定(使用
绑定操作。SetBinding
),则即使应用程序未运行,绑定也可以正常工作


因此在这种情况下,我认为问题在于
窗口
尚未加载,因此可视化树尚未准备就绪,因此
DataContext
传播不起作用,因此绑定没有源。

这是可能的,但您必须这样做:

    var win = new MainWindow();
    var vm = new ViewModel(); // Remove this line
    win.DataContext = vm;  // Remove this line
    vm.Test = "Testing";  // Remove this line
在XAML中,更改以下内容:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:YourViewModelNameSpace"  // Add this, change to correct namespace
    Title="MainWindow" Height="350" Width="260">
<Window.DataContext> // Add this tag and contents
    <local:ViewModel/> // This instantiates the ViewModel class and assigns it to DataContext
</Window.DataContext>
<StackPanel>
    <TextBox Height="23" x:Name="TextBox" TextWrapping="Wrap" Text="{Binding Test, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
在XAML中,您可能必须删除解释性注释

我就是这样得到的:

@Thomas
。没有实际运行应用程序?
据我所知,不需要显示窗口;这必须在运行时完成。因此我建议在设计时显示
测试标签(然后绑定也可以工作)@BenRobinson我想为我的WPF应用程序进行单元测试,但如果可能的话,我想避免实际运行它的任何可视部分。
public class ViewModel
{
    public ViewModel()  // Add this constructor
    {
        Test = "Testing";
    }

    public string Test { get; set; }
}