私はキャンバスを持っています。 this solutionに類似しているか、またはItemsControl
を使用している多くの他のものです。MVVMパターンに従った画像としてWPFキャンバスを保存する
今、ICommandにバインドするボタンが必要です。このコマンドは、画像を保存できるViewModelクラスのメソッドを呼び出す必要があります。 保存方法ははっきりしていますが、MVVMパターンに従ってバインディングを実行するにはどうすればよいですか?
私はキャンバスを持っています。 this solutionに類似しているか、またはItemsControl
を使用している多くの他のものです。MVVMパターンに従った画像としてWPFキャンバスを保存する
今、ICommandにバインドするボタンが必要です。このコマンドは、画像を保存できるViewModelクラスのメソッドを呼び出す必要があります。 保存方法ははっきりしていますが、MVVMパターンに従ってバインディングを実行するにはどうすればよいですか?
<Button Content="Save"
Command="{Binding SaveCanvasCommand}"
CommandParameter="{Binding ElenementName=myCanvas}" ?>
<Canvas x:Name="myCanvas">
<!-- Stuff to save -->
</Canvas>
そしてどこかにあるのViewModelまたはコマンドは、あなたがMVVMを使用してバインドする方法を探してい
void SaveCanvasCommandExecute(object parameter)
{
UIElement toSave = (UIElement)parameter;
//.. You'd probably use RenderTargetBitmap here to save toSave.
}
あなたのViewModelあなたは添付ビヘイビアを使用することができますのUI要素参照したくない場合:
:internal static class Behaviours
{
public static readonly DependencyProperty SaveCanvasProperty =
DependencyProperty.RegisterAttached("SaveCanvas", typeof(bool), typeof(Behaviours),
new UIPropertyMetadata(false, OnSaveCanvas));
public static void SetSaveCanvas(DependencyObject obj, bool value)
{
obj.SetValue(SaveCanvasProperty, value);
}
public static bool GetSaveCanvas(DependencyObject obj)
{
return (bool)obj.GetValue(SaveCanvasProperty);
}
private static void OnSaveCanvas(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
// Save code.....
}
}
}
は、その後、あなたのViewModelにあなたのViewModelにも、プロパティを設定し、あなたのコマンドを持っています
public ICommand SaveCanvasCommand
{
get
{
if (_saveCanvasCommand == null)
_saveCanvasCommand = new RelayCommand(() => { IsSaveCanvas = true; });
return _saveCanvasCommand;
}
}
そして、あなたのビューにバインドされたプロパティ:
public bool IsSaveCanvas
{
get { return _isSaveCanvas; }
set
{
_isSaveCanvas = value;
RaisePropertyChanged("IsSaveCanvas");
}
}
のTh
があなたの接続動作にあなたのViewModelプロパティの値をバインドしControl
にTrigger
を追加します:その後、
<UserControl.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSaveCanvas}" Value="True">
<Setter Property="wpfApplication1:Behaviours.SaveCanvas" Value="True"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsSaveCanvas}" Value="False">
<Setter Property="wpfApplication1:Behaviours.SaveCanvas" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Style>
とのおButton
/MenuItem
をバインドするXAMLでそれをすべてをフック途中、このようになります。 viewmodels保存コマンド:あなたはCommandParameterを使用してのViewModelのSaveメソッドにキャンバスを渡すことができ
<Canvas.ContextMenu>
<MenuItem Header="Save" Command="{Binding SaveCanvasCommand}"/>
</Canvas.ContextMenu>
必要があるだろうか? (MVVMライトRelayCommand) – whoisthis