2016-08-06 12 views
0

別のxamlファイル(FirstView.xamlとSecondView.xaml)に2つのビューを持つアプリケーションがあります。デフォルトモードでアプリケーションがFirstView.xamlからビューを生成します。MVVMを使用すると、App.configを使用して動的にビューを生成できます

<Application x:Class="WpfDemo.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfDemo" 
     StartupUri="View\FirstView.xaml"> 
<Application.Resources> 

</Application.Resources> 

私はラインを編集することにより、第2のビューに切り替えることができます。

StartupUri="View\SecondView.xaml" 

これは正常に動作し、コンパイル時に私は実行時にこれを達成したいと思います。私は、次の内容でアプリケーション設定を作成しました:

<applicationSettings> 
    <WpfDemo.Properties.Settings> 
     <setting name="View" serializeAs="String"> 
      <value>FirstView</value> 
     </setting> 
    </WpfDemo.Properties.Settings> 
</applicationSettings> 

私はApp.configファイルの内容を読み取ることができます。

string view = Properties.Settings.Default.View.ToString(); 

私は、実行時にview変数に応じてビューを切り替えたいです時間。

+0

なぜこれをやりたいのですか?私は自己破壊的な行動に魅了されているので、私は興味があります... – Will

答えて

3

最初の手順:App.xamlからStartupUriを削除します。

第二ステップ:あなたのApp.xamlのコードビハインドで

protected override void OnStartup(StartupEventArgs e) { 
      Uri dynamicUri = null; 
      string view = Properties.Settings.Default.View.ToString(); 
      var result = Uri.TryCreate(view, UriKind.RelativeOrAbsolute, out dynamicUri); 
      if (!result) throw new ApplicationException("Invalid settings found."); 
      this.StartupUri = dynamicUri; 
      base.OnStartup(e); 
     } 

質問と回答次の両方のんはMVVMとは何の関係もありません。このような動作には、MVBMソリューションはありません。なぜなら、データバインディングに入る前にすべてが行われなければならないからです。

関連する問題