2017-08-10 16 views
0

親ウィンドウのフレーム内にUserControlがあります。ユーザーコントロールでは、親ウィンドウのボタンをトグルするときに編集が必要なテキストボックスがあります。私は正常に動作し、データトリガを取得するにはどうすればよいWPF MainWindowは、ViewModelを介してUserControlのプロパティを切り替えます。

UserControl.xaml

<UserControl.Resources> 
    <ResourceDictionary> 
     <Style x:Key="TextBoxEdit" TargetType="TextBox"> 
      <Setter Property="IsReadOnly" Value="True" /> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding CanEdit}" Value="True"> 
        <Setter Property="IsReadOnly" Value="False" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ResourceDictionary> 

</UserControl.Resources> 
<Grid> 
    <TextBox 
     x:Name="EditTextBox" 
     HorizontalAlignment="Left" 
     VerticalAlignment="Top" 
     Style="{StaticResource TextBoxEdit}" 
     Text="Edit me" /> 
</Grid> 

MainWindow.xaml

<Controls:MetroWindow.DataContext> 
    <local:ViewModel/> 
</Controls:MetroWindow.DataContext> 

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto" /> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 
    <ToggleButton x:Name="EditButton" HorizontalAlignment="Center" VerticalAlignment="Top" IsChecked="{Binding CanEdit}">Edit</ToggleButton> 
    <Frame Grid.Row="1" Source="Home.xaml" /> 
</Grid> 

のViewModel

public class ViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private bool canEdit; 
    public bool CanEdit 
    { 
     get { return canEdit; } 
     set 
     { 
      canEdit = value; 
      OnPropertyChanged("CanEdit"); 
     } 
    } 

    private void OnPropertyChanged(string propertyName) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

?ユーザーコントロールの別のビューモデルを作成し、2つのビューモデル間で値を通信する最も良い方法はありますか?もしそうなら、どうすればいいのですか?

+0

フレームを使用する特別な理由はありますか? – mm8

+0

私はフレームの内容を別のusercontrolsに変更するナビゲーションバーを持つ1つのメインウィンドウを持って、これを行うための最善の方法だと思った。よりよい選択肢がありますか? –

+0

Home.xamlはUserControlですか? – mm8

答えて

0

usercontrolの別のビューモデルを作成し、2つのビューモデル間で値を通信する最も良い方法はありますか?

最も一般的な方法は、彼らの両方が同じプロパティにバインドすることができますので、単純に親ウィンドウのDataContextを継承するUserControlのためになります。

Frameを使用している場合、これはすぐには機能しません。

あなたはContentControlFrameを置き換えることができ、次のいずれか

<ToggleButton x:Name="EditButton" IsChecked="{Binding CanEdit}">Edit</ToggleButton> 
<ContentControl> 
    <local:Home /> 
</ContentControl> 

それとも、FrameためDataContextChangedイベントを処理し、ここで@Joeホワイトによって示唆されているように、明示的にそのContentDataContextを設定できますpage.DataContext not inherited from parent Frame?

+0

これは私のテストプロジェクトでどのようにしたいのですか?実際のアプリケーションにはいくつか問題がありますが、私はその構造を再考する必要があると思います。しかし、あなたの答えはとても助けになったので、ありがとう。 –

関連する問題