1

ViewModelのプロパティにバインドされたテキストボックス内のテキストを表示する単純なウィンドウを備えたwpfアプリケーションがあります。アプリケーションを実行すると、テキストボックスにテキストが表示されますが、白ベースのテストを実行すると、ランダムに異なる結果が得られます。

  • ほとんどの場合、バインドされておらず、テストは失敗します。
  • バインドされている場合もありますが(ウィンドウ内のテキストは白で表示されます)、コードがウィンドウを取得しようとすると、白は例外をスローします。
  • 時々(本当に少数)それは動作します。

私が実行しようとしているコードは次のとおりです。

<Window x:Class="Sample.Tests.Wpf.MainWindow"     
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">   
  <Grid>
    <TextBox Height="23"
             HorizontalAlignment="Left"
             Margin="22,19,0,0"
             Name="name"
             Text="{Binding Path=CountryName}" 
             VerticalAlignment="Top"
             Width="120" />
  </Grid>
</Window>

背後にあるコード:

namespace Sample.Tests.Wpf
{
  public partial class MainWindow
  {
    public MainWindow()
    {
      InitializeComponent();
      Loaded += delegate { DataContext = new MainWindowViewModel
                                         {
                                           CountryName = "Argentina"
                                         };
                          };
    }
  }
}

テストは次のようになります。

var app = Application.Launch("Sample.Tests.Wpf.exe");
var window = app.GetWindow("MainWindow");
Assert.IsNotNull(window);
var textbox = window.Get<TextBox>("name");
Assert.AreEqual("Argentina", textbox.Text);

何か案が?

4

1 に答える 1

1

Loadedイベントは、ウィンドウがレンダリングされる直前まで発生しません。私の推測では、それはそのイベントのタイミングと関係があると思います。

応答を待つのではなく、DataContextを割り当てるだけで機能しますか?

namespace Sample.Tests.Wpf
{
    public partial class MainWindow
    {
         public MainWindow()
         {
              InitializeComponent();
              DataContext = new MainWindowViewModel
                                     {
                                       CountryName = "Argentina"
                                     };
         }
     }
}
于 2011-11-28T22:58:06.633 に答える