WPF define Command in usercontrol and used in mvvm, Rotated circle as usercontrol and used in multiple times
//usercontrol.xaml <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="0" Panel.ZIndex="0" Background="LightCyan"> <behavior:Interaction.Triggers> <behavior:EventTrigger EventName="MouseLeftButtonDown"> <behavior:InvokeCommandAction Command="{Binding UCLeftClickCommand}"/> </behavior:EventTrigger> </behavior:Interaction.Triggers> </Grid> //usercontrol.xaml.cs public ICommand UCLeftClickCommand { get { return (ICommand)GetValue(UCLeftClickCommandProperty); } set { SetValue(UCLeftClickCommandProperty, value); } } // Using a DependencyProperty as the backing store for UCLeftClickCommand. This enables animation, styling, binding, etc... public static readonly DependencyProperty UCLeftClickCommandProperty = DependencyProperty.Register("UCLeftClickCommand", typeof(ICommand), typeof(UCRotateCircle), new PropertyMetadata(null)); //main view UCLeftClickCommand="{Binding DataContext.FirstLeftClickCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" //mainvm.cs private ICommand firstLeftClickCommand; public ICommand FirstLeftClickCommand { get { if (firstLeftClickCommand == null) { firstLeftClickCommand = new DelCommand(FirstLeftClickCommandExecuted, FirstLeftClickCommandCanExecute); } return firstLeftClickCommand; } } private bool FirstLeftClickCommandCanExecute(object? obj) { return true; } private void FirstLeftClickCommandExecuted(object? obj) { ToggleBorderTransform("firstRotateCircle"); }
//
//usercontrol.xaml <UserControl x:Class="WpfApp159.UCRotateCircle" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApp159" xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <local:SizeConverter x:Key="sizeConverter"/> </UserControl.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="10*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" FontSize="15" Foreground="Red" FontWeight="Bold" HorizontalAlignment="Center" Text="{Binding UCRotatedAngleStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <Ellipse x:Name="elp" Panel.ZIndex="2" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Width="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}, Converter={StaticResource sizeConverter}, ConverterParameter=1.5}" Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}, Converter={StaticResource sizeConverter}, ConverterParameter=1.5}" MouseDown="elp_MouseDown" MouseMove="elp_MouseMove" MouseUp="elp_MouseUp" RenderTransformOrigin="0.5,0.5"> <Ellipse.RenderTransform> <RotateTransform x:Name="rotateTransform"/> </Ellipse.RenderTransform> <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="Orange" Offset="0.0"/> <GradientStop Color="Orange" Offset="0.2"/> <GradientStop Color="Yellow" Offset="0.2"/> <GradientStop Color="Yellow" Offset="0.4"/> <GradientStop Color="Green" Offset="0.4"/> <GradientStop Color="Green" Offset="0.495"/> <GradientStop Color="Red" Offset="0.495"/> <GradientStop Color="Red" Offset="0.505"/> <GradientStop Color="Green" Offset="0.505"/> <GradientStop Color="Green" Offset="0.6"/> <GradientStop Color="Cyan" Offset="0.6"/> <GradientStop Color="Cyan" Offset="0.8"/> <GradientStop Color="Blue" Offset="0.8"/> <GradientStop Color="Blue" Offset="1.0"/> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <Border Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Panel.ZIndex="1" HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="Black" Width="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}, Converter={StaticResource sizeConverter}, ConverterParameter=1.2}" Height="20" RenderTransformOrigin="0.5,0.5" > <Border.RenderTransform> <RotateTransform x:Name="borderRotateTransform" Angle="{Binding UCBorderAnge,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> </Border.RenderTransform> </Border> <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="0" Panel.ZIndex="0" Background="LightCyan"> <behavior:Interaction.Triggers> <behavior:EventTrigger EventName="MouseLeftButtonDown"> <behavior:InvokeCommandAction Command="{Binding UCLeftClickCommand}"/> </behavior:EventTrigger> </behavior:Interaction.Triggers> </Grid> <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="1" Panel.ZIndex="0" Background="LightBlue"> <behavior:Interaction.Triggers> <behavior:EventTrigger EventName="MouseLeftButtonDown"> <behavior:InvokeCommandAction Command="{Binding UCRightClickCommand}"/> </behavior:EventTrigger> </behavior:Interaction.Triggers> </Grid> </Grid> </UserControl> //usercontrol.xaml.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp159 { /// <summary> /// Interaction logic for UCRotateCircle.xaml /// </summary> public partial class UCRotateCircle : UserControl, INotifyPropertyChanged { public UCRotateCircle() { InitializeComponent(); this.DataContext = this; } Point originPt { get; set; } Point currentPt { get; set; } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); Point tempPt = new Point(elp.ActualWidth / 2, elp.ActualHeight / 2); originPt = elp.TranslatePoint(tempPt, this); } public double UCConverterParameter { get { return (double)GetValue(UCConverterParameterProperty); } set { SetValue(UCConverterParameterProperty, value); } } // Using a DependencyProperty as the backing store for UCConverterParameter. This enables animation, styling, binding, etc... public static readonly DependencyProperty UCConverterParameterProperty = DependencyProperty.Register("UCConverterParameter", typeof(double), typeof(UCRotateCircle), new PropertyMetadata(2.0d)); public string UCRotatedAngleStr { get { return (string)GetValue(UCRotatedAngleStrProperty); } set { SetValue(UCRotatedAngleStrProperty, value); } } // Using a DependencyProperty as the backing store for UCRotatedAngleStr. This enables animation, styling, binding, etc... public static readonly DependencyProperty UCRotatedAngleStrProperty = DependencyProperty.Register("UCRotatedAngleStr", typeof(string), typeof(UCRotateCircle), new PropertyMetadata("0")); public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged(string propName) { var handler = PropertyChanged; if (handler != null) { handler?.Invoke(this, new PropertyChangedEventArgs(propName)); } } private double convertPara = 2.0d; public double ConvertPara { get { return convertPara; } set { if (value != convertPara) { convertPara = value; OnPropertyChanged(nameof(ConvertPara)); } } } private void elp_MouseDown(object sender, MouseButtonEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { currentPt = e.GetPosition(this); elp.CaptureMouse(); } } private void elp_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { Vector prevVec = Point.Subtract(currentPt, originPt); Point newPt = e.GetPosition(this); Vector newVec = Point.Subtract(newPt, originPt); double deltaAngle = Vector.AngleBetween(prevVec, newVec); rotateTransform.Angle += deltaAngle; currentPt = newPt; UCRotatedAngleStr = Math.Round(rotateTransform.Angle, 2).ToString(); System.Diagnostics.Debug.WriteLine($"{deltaAngle},{rotateTransform.Angle}"); } } private void elp_MouseUp(object sender, MouseButtonEventArgs e) { if (e.LeftButton == MouseButtonState.Released) { elp.ReleaseMouseCapture(); } } public double UCBorderAnge { get { return (double)GetValue(UCBorderAngeProperty); } set { SetValue(UCBorderAngeProperty, value); } } // Using a DependencyProperty as the backing store for UCBorderAnge. This enables animation, styling, binding, etc... public static readonly DependencyProperty UCBorderAngeProperty = DependencyProperty.Register("UCBorderAnge", typeof(double), typeof(UCRotateCircle), new PropertyMetadata(45.0d)); public ICommand UCLeftClickCommand { get { return (ICommand)GetValue(UCLeftClickCommandProperty); } set { SetValue(UCLeftClickCommandProperty, value); } } // Using a DependencyProperty as the backing store for UCLeftClickCommand. This enables animation, styling, binding, etc... public static readonly DependencyProperty UCLeftClickCommandProperty = DependencyProperty.Register("UCLeftClickCommand", typeof(ICommand), typeof(UCRotateCircle), new PropertyMetadata(null)); public ICommand UCRightClickCommand { get { return (ICommand)GetValue(UCRightClickCommandProperty); } set { SetValue(UCRightClickCommandProperty, value); } } // Using a DependencyProperty as the backing store for UCRightClickCommand. This enables animation, styling, binding, etc... public static readonly DependencyProperty UCRightClickCommandProperty = DependencyProperty.Register("UCRightClickCommand", typeof(ICommand), typeof(UCRotateCircle), new PropertyMetadata(null)); } public class SizeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double dValue = 0.0, dPara = 0.0; if (double.TryParse(value?.ToString(), out dValue) && double.TryParse(parameter?.ToString(), out dPara) && dPara > 0) { return dValue / dPara; } return dValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class DelCommand : ICommand { private Action<object?> execute; private Predicate<object?> canExecute; public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null) { execute = executeValue; canExecute = canExecuteValue; } public event EventHandler? CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object? parameter) { if (canExecute == null) { return true; } return canExecute(parameter); } public void Execute(object? parameter) { execute(parameter); } } } //main.xaml <Window x:Class="WpfApp159.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp159" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <local:UCRotateCircle Grid.Row="0" Grid.Column="0" x:Name="firstRotateCircle" UCBorderAnge="{Binding DataContext.FirstBorderAnge,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" UCLeftClickCommand="{Binding DataContext.FirstLeftClickCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" UCRightClickCommand="{Binding DataContext.FirstRightClickCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/> <local:UCRotateCircle Grid.Row="0" Grid.Column="1" x:Name="secondRotateCircle" UCBorderAnge="{Binding DataContext.SecondBorderAnge,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" UCLeftClickCommand="{Binding DataContext.SecondToggleBorderAngleCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" UCRightClickCommand="{Binding DataContext.SecondToggleBorderAngleCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/> <local:UCRotateCircle Grid.Row="1" Grid.Column="0" x:Name="thirdRotateCircle" UCBorderAnge="{Binding DataContext.ThirdBorderAnge,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" UCLeftClickCommand="{Binding DataContext.ThirdToggleBorderAngleCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" UCRightClickCommand="{Binding DataContext.ThirdToggleBorderAngleCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/> <local:UCRotateCircle Grid.Row="1" Grid.Column="1" x:Name="forthRotateCircle" UCBorderAnge="{Binding DataContext.ForthBorderAnge,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" UCLeftClickCommand="{Binding DataContext.ForthToggleBorderAngleCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" UCRightClickCommand="{Binding DataContext.ForthToggleBorderAngleCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/> </Grid> </Window> //mainvm.cs using System.ComponentModel; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Converters; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp159 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var vm = new MainVM(this); this.DataContext = vm; } } public class MainVM : INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged(string propName) { var handler = PropertyChanged; if (handler != null) { handler?.Invoke(this, new PropertyChangedEventArgs(propName)); } } public Window win { get; set; } public MainVM(Window winValue) { win = winValue; } private void ToggleBorderTransform(string ucRotateCircleName) { var rotateCircle = win.FindName(ucRotateCircleName) as UCRotateCircle; if (rotateCircle != null) { var borderTransform = rotateCircle.FindName("borderRotateTransform") as RotateTransform; if (borderTransform != null) { borderTransform.Angle = borderTransform.Angle == 45 ? 135 : 45; } } } #region First Rotate Circle private double firstBorderAnge = 45.0d; public double FirstBorderAnge { get { return firstBorderAnge; } set { if (value != firstBorderAnge) { firstBorderAnge = value; OnPropertyChanged(nameof(FirstBorderAnge)); } } } private ICommand firstLeftClickCommand; public ICommand FirstLeftClickCommand { get { if (firstLeftClickCommand == null) { firstLeftClickCommand = new DelCommand(FirstLeftClickCommandExecuted, FirstLeftClickCommandCanExecute); } return firstLeftClickCommand; } } private bool FirstLeftClickCommandCanExecute(object? obj) { return true; } private void FirstLeftClickCommandExecuted(object? obj) { ToggleBorderTransform("firstRotateCircle"); } private ICommand firstRightClickCommand; public ICommand FirstRightClickCommand { get { if (firstRightClickCommand == null) { firstRightClickCommand = new DelCommand(FirstRightClickCommandExecuted, FirstRightClickCommandCanExecute); } return firstRightClickCommand; } } private bool FirstRightClickCommandCanExecute(object? obj) { return true; } private void FirstRightClickCommandExecuted(object? obj) { ToggleBorderTransform("firstRotateCircle"); } #endregion #region Second Rotate Circle private double secondBorderAnge = 45.0d; public double SecondBorderAnge { get { return secondBorderAnge; } set { if (value != secondBorderAnge) { secondBorderAnge = value; OnPropertyChanged(nameof(SecondBorderAnge)); } } } private ICommand secondToggleBorderAngleCommand; public ICommand SecondToggleBorderAngleCommand { get { if (secondToggleBorderAngleCommand == null) { secondToggleBorderAngleCommand = new DelCommand(SecondToggleBorderAngleCommandExecuted, SecondToggleBorderAngleCommandCanExecute); } return secondToggleBorderAngleCommand; } } private bool SecondToggleBorderAngleCommandCanExecute(object? obj) { return true; } private void SecondToggleBorderAngleCommandExecuted(object? obj) { ToggleBorderTransform("secondRotateCircle"); } #endregion #region Third Rotate Circle private double thirdBorderAnge = 45.0d; public double ThirdBorderAnge { get { return thirdBorderAnge; } set { if (value != thirdBorderAnge) { thirdBorderAnge = value; OnPropertyChanged(nameof(ThirdBorderAnge)); } } } private ICommand thirdToggleBorderAngleCommand; public ICommand ThirdToggleBorderAngleCommand { get { if(thirdToggleBorderAngleCommand == null) { thirdToggleBorderAngleCommand = new DelCommand(ThirdToggleBorderAngleCommandExecuted, ThirdToggleBorderAngleCommandCanExecute); } return thirdToggleBorderAngleCommand; } } private bool ThirdToggleBorderAngleCommandCanExecute(object? obj) { return true; } private void ThirdToggleBorderAngleCommandExecuted(object? obj) { ToggleBorderTransform("thirdRotateCircle"); } #endregion #region Forth Rotate Circle private ICommand forthToggleBorderAngleCommand; public ICommand ForthToggleBorderAngleCommand { get { if(forthToggleBorderAngleCommand == null) { forthToggleBorderAngleCommand = new DelCommand(ForthToggleBorderAngleCommandExecuted, ForthToggleBorderAngleCommandCanExecute); } return forthToggleBorderAngleCommand; } } private bool ForthToggleBorderAngleCommandCanExecute(object? obj) { return true; } private void ForthToggleBorderAngleCommandExecuted(object? obj) { ToggleBorderTransform("forthRotateCircle"); }
private double forthBorderAnge;
public double ForthBorderAnge
{
get
{
return forthBorderAnge;
}
set
{
if(value!= forthBorderAnge)
{
forthBorderAnge = value;
OnPropertyChanged(nameof (ForthBorderAnge));
}
}
}
#endregion } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2021-03-02 C# 8 using declarations