如何在C#中使用Border.BackgroundSizing并控制BackgroundTransition时长
解决BrushTransition无法精准控制过渡时长的问题
问题根源
你当前的实现里,无论是XAML中声明的BrushTransition,还是后台代码新建的BrushTransition实例,都没有显式设置Duration属性,所以过渡动画会使用系统默认时长,无法达到你想要的精准控制效果。另外后台Entered方法里每次都重新创建BrushTransition并赋值,属于冗余操作,而且新实例也没配置Duration,自然没法生效。
可行解决方案
方案1:直接在XAML中配置过渡时长
这是最简单的方式,直接给BrushTransition添加Duration属性,指定你需要的过渡时间:
修改后的XAML代码(以b1为例,b2同理):
<Border x:Name="b1" Width="150沙包Concib远征军皮 Things principles Optimization Gregory全文 点击 -_r == r1) { r1.Stroke = new SolidColorBrush(Colors.Purple); r1.StrokeThickness = 2; b1.Background = new SolidColorBrush(Colors.DarkGray); } else if (_r == r2) { r2.Stroke = new SolidColorBrush(Colors.Purple); r2.StrokeThickness = 2; b2.Background = new SolidColorBrush(Colors.DarkGray); } } public void Exited(object sender, RoutedEventArgs e) { if (sender is not Microsoft.UI.Xaml.Shapes.Rectangle _r) return; if (_r == r1) { b1.Background = new SolidColorBrush(Colors.Transparent); r1.Stroke = new SolidColorBrush(Colors.Transparent); r1.StrokeThickness = .5; } else if (_r == r2) { b2.Background = new SolidColorBrush(Colors.Transparent); r2.Stroke = new SolidColorBrush(Colors.Transparent); r2.StrokeThickness = .5; } } }
方案2:后台动态控制过渡时长
如果需要根据逻辑动态调整过渡时长,可以在后台创建BrushTransition实例时显式设置Duration,再赋值给Border:
public void Entered(object sender, RoutedEventArgs e) { if (sender is not Microsoft.UI.Xaml.Shapes.Rectangle _r) return; // 创建带指定时长的过渡实例,这里设置为1秒 var customTransition = new BrushTransition { Duration = TimeSpan.FromSeconds(1) }; if (_r == r1) { r1.Stroke = new SolidColorBrush(Colors.Purple); r1.StrokeThickness = 2; b1.BackgroundTransition = customTransition; b1.Background = new SolidColorBrush(Colors.DarkGray); } else if (_r == r2) { r2.Stroke = new SolidColorBrush(Colors.Purple); r2.StrokeThickness = 2; b2.BackgroundTransition = customTransition; b2.Background = new SolidColorBrush(Colors.DarkGray); } }
额外说明
你代码中的BackgroundSizing属性是用来控制背景是否延伸到边框区域的,和过渡动画的时长没有关系,不需要每次触发指针事件都重新设置,完全可以移除这部分冗余代码。
内容的提问来源于stack exchange,提问作者jv1597
相关产品推荐
相关产品推荐

