uwp-xaml 相关问题

此标记用于Windows 10上Windows-Store-Apps特有的XAML UI框架,是通用Windows平台(UWP)的一部分。

如何访问引用的 UWP 类库中包含的资源字典?

我正在考虑为 UWP 应用程序实现组件库的想法。 我正在努力解决的一件事是从组件库中的资源库中访问资源...

回答 1 投票 0

使用 XAML 的 UWP 应用中的垂直文本

我想在边框元素内部垂直写入文本。如图所示。 我尝试过使用 RenderTransform 与此代码 我想在边框元素内部垂直写入文本。如图所示。 我尝试使用 RenderTransform 与此代码 <Border Width="80" Background="Teal"> <TextBlock Text="CATEGORIES" Foreground="White" FontFamily="Segoe UI Black" FontSize="30"> <TextBlock.RenderTransform> <RotateTransform Angle="-90" /> </TextBlock.RenderTransform> </TextBlock> </Border> 这会垂直旋转文本,但 TextBlock 采用变换之前的旧高度和宽度值,并且不会完全显示文本。因此文本在 80 像素(边框元素的宽度)后被截断。在搜索时我发现使用 LayoutTransform 可以解决问题,但它在 UWP 应用程序中不可用。如何在 UWP XAML 中执行此操作? 这在 UWP 上也对我有用。只需使用here发布的类,而不是帖子中的类。并且还复制博客文章中的样式。 编辑:onedrive 链接不再有效。所以我在这里发布代码。 创建一个新类LayoutTransformer using System; using System.Diagnostics.CodeAnalysis; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace Common { /// <summary> /// Represents a control that applies a layout transformation to its Content. /// </summary> /// <QualityBand>Preview</QualityBand> [TemplatePart(Name = TransformRootName, Type = typeof(Grid))] [TemplatePart(Name = PresenterName, Type = typeof(ContentPresenter))] public sealed class LayoutTransformer : ContentControl { /// <summary> /// Name of the TransformRoot template part. /// </summary> private const string TransformRootName = "TransformRoot"; /// <summary> /// Name of the Presenter template part. /// </summary> private const string PresenterName = "Presenter"; /// <summary> /// Gets or sets the layout transform to apply on the LayoutTransformer /// control content. /// </summary> /// <remarks> /// Corresponds to UIElement.LayoutTransform. /// </remarks> public Transform LayoutTransform { get { return (Transform)GetValue(LayoutTransformProperty); } set { SetValue(LayoutTransformProperty, value); } } /// <summary> /// Identifies the LayoutTransform DependencyProperty. /// </summary> public static readonly DependencyProperty LayoutTransformProperty = DependencyProperty.Register( "LayoutTransform", typeof(Transform), typeof(LayoutTransformer), new PropertyMetadata(null, LayoutTransformChanged)); /// <summary> /// Gets the child element being transformed. /// </summary> private FrameworkElement Child { get { // Preferred child is the content; fall back to the presenter itself return (null != _contentPresenter) ? (_contentPresenter.Content as FrameworkElement ?? _contentPresenter) : null; } } // Note: AcceptableDelta and DecimalsAfterRound work around double arithmetic rounding issues on Silverlight. private const double AcceptableDelta = 0.0001; private const int DecimalsAfterRound = 4; private Panel _transformRoot; private ContentPresenter _contentPresenter; private MatrixTransform _matrixTransform; private Matrix _transformation; private Size _childActualSize = Size.Empty; public LayoutTransformer() { // Associated default style DefaultStyleKey = typeof(LayoutTransformer); // Can't tab to LayoutTransformer IsTabStop = false; #if SILVERLIGHT // Disable layout rounding because its rounding of values confuses things UseLayoutRounding = false; #endif } /// <summary> /// Builds the visual tree for the LayoutTransformer control when a new /// template is applied. /// </summary> protected override void OnApplyTemplate() { // Apply new template base.OnApplyTemplate(); // Find template parts _transformRoot = GetTemplateChild(TransformRootName) as Grid; _contentPresenter = GetTemplateChild(PresenterName) as ContentPresenter; _matrixTransform = new MatrixTransform(); if (null != _transformRoot) { _transformRoot.RenderTransform = _matrixTransform; } // Apply the current transform ApplyLayoutTransform(); } /// <summary> /// Handles changes to the Transform DependencyProperty. /// </summary> /// <param name="o">Source of the change.</param> /// <param name="e">Event args.</param> private static void LayoutTransformChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { // Casts are safe because Silverlight is enforcing the types ((LayoutTransformer)o).ProcessTransform((Transform)e.NewValue); } /// <summary> /// Applies the layout transform on the LayoutTransformer control content. /// </summary> /// <remarks> /// Only used in advanced scenarios (like animating the LayoutTransform). /// Should be used to notify the LayoutTransformer control that some aspect /// of its Transform property has changed. /// </remarks> public void ApplyLayoutTransform() { ProcessTransform(LayoutTransform); } /// <summary> /// Processes the Transform to determine the corresponding Matrix. /// </summary> /// <param name="transform">Transform to process.</param> private void ProcessTransform(Transform transform) { // Get the transform matrix and apply it _transformation = RoundMatrix(GetTransformMatrix(transform), DecimalsAfterRound); if (null != _matrixTransform) { _matrixTransform.Matrix = _transformation; } // New transform means re-layout is necessary InvalidateMeasure(); } /// <summary> /// Walks the Transform(Group) and returns the corresponding Matrix. /// </summary> /// <param name="transform">Transform(Group) to walk.</param> /// <returns>Computed Matrix.</returns> private Matrix GetTransformMatrix(Transform transform) { if (null != transform) { // WPF equivalent of this entire method: // return transform.Value; // Process the TransformGroup TransformGroup transformGroup = transform as TransformGroup; if (null != transformGroup) { Matrix groupMatrix = Matrix.Identity; foreach (Transform child in transformGroup.Children) { groupMatrix = MatrixMultiply(groupMatrix, GetTransformMatrix(child)); } return groupMatrix; } // Process the RotateTransform RotateTransform rotateTransform = transform as RotateTransform; if (null != rotateTransform) { double angle = rotateTransform.Angle; double angleRadians = (2 * Math.PI * angle) / 360; double sine = Math.Sin(angleRadians); double cosine = Math.Cos(angleRadians); return new Matrix(cosine, sine, -sine, cosine, 0, 0); } // Process the ScaleTransform ScaleTransform scaleTransform = transform as ScaleTransform; if (null != scaleTransform) { double scaleX = scaleTransform.ScaleX; double scaleY = scaleTransform.ScaleY; return new Matrix(scaleX, 0, 0, scaleY, 0, 0); } // Process the SkewTransform SkewTransform skewTransform = transform as SkewTransform; if (null != skewTransform) { double angleX = skewTransform.AngleX; double angleY = skewTransform.AngleY; double angleXRadians = (2 * Math.PI * angleX) / 360; double angleYRadians = (2 * Math.PI * angleY) / 360; return new Matrix(1, angleYRadians, angleXRadians, 1, 0, 0); } // Process the MatrixTransform MatrixTransform matrixTransform = transform as MatrixTransform; if (null != matrixTransform) { return matrixTransform.Matrix; } // TranslateTransform has no effect in LayoutTransform } // Fall back to no-op transformation return Matrix.Identity; } /// <summary> /// Provides the behavior for the "Measure" pass of layout. /// </summary> /// <param name="availableSize">The available size that this element can give to child elements.</param> /// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns> protected override Size MeasureOverride(Size availableSize) { FrameworkElement child = Child; if ((null == _transformRoot) || (null == child)) { // No content, no size return Size.Empty; } //DiagnosticWriteLine("MeasureOverride < " + availableSize); Size measureSize; if (_childActualSize == Size.Empty) { // Determine the largest size after the transformation measureSize = ComputeLargestTransformedSize(availableSize); } else { // Previous measure/arrange pass determined that Child.DesiredSize was larger than believed //DiagnosticWriteLine(" Using _childActualSize"); measureSize = _childActualSize; } // Perform a mesaure on the _transformRoot (containing Child) //DiagnosticWriteLine(" _transformRoot.Measure < " + measureSize); _transformRoot.Measure(measureSize); //DiagnosticWriteLine(" _transformRoot.DesiredSize = " + _transformRoot.DesiredSize); // WPF equivalent of _childActualSize technique (much simpler, but doesn't work on Silverlight 2) // // If the child is going to render larger than the available size, re-measure according to that size // child.Arrange(new Rect()); // if (child.RenderSize != child.DesiredSize) // { // _transformRoot.Measure(child.RenderSize); // } // Transform DesiredSize to find its width/height Rect transformedDesiredRect = RectTransform(new Rect(0, 0, _transformRoot.DesiredSize.Width, _transformRoot.DesiredSize.Height), _transformation); Size transformedDesiredSize = new Size(transformedDesiredRect.Width, transformedDesiredRect.Height); // Return result to allocate enough space for the transformation //DiagnosticWriteLine("MeasureOverride > " + transformedDesiredSize); return transformedDesiredSize; } /// <summary> /// Provides the behavior for the "Arrange" pass of layout. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> /// <remarks> /// Using the WPF paramater name finalSize instead of Silverlight's finalSize for clarity /// </remarks> protected override Size ArrangeOverride(Size finalSize) { FrameworkElement child = Child; if ((null == _transformRoot) || (null == child)) { // No child, use whatever was given return finalSize; } //DiagnosticWriteLine("ArrangeOverride < " + finalSize); // Determine the largest available size after the transformation Size finalSizeTransformed = ComputeLargestTransformedSize(finalSize); if (IsSizeSmaller(finalSizeTransformed, _transformRoot.DesiredSize)) { // Some elements do not like being given less space than they asked for (ex: TextBlock) // Bump the working size up to do the right thing by them //DiagnosticWriteLine(" Replacing finalSizeTransformed with larger _transformRoot.DesiredSize"); finalSizeTransformed = _transformRoot.DesiredSize; } //DiagnosticWriteLine(" finalSizeTransformed = " + finalSizeTransformed); // Transform the working size to find its width/height Rect transformedRect = RectTransform(new Rect(0, 0, finalSizeTransformed.Width, finalSizeTransformed.Height), _transformation); // Create the Arrange rect to center the transformed content Rect finalRect = new Rect( -transformedRect.Left + ((finalSize.Width - transformedRect.Width) / 2), -transformedRect.Top + ((finalSize.Height - transformedRect.Height) / 2), finalSizeTransformed.Width, finalSizeTransformed.Height); // Perform an Arrange on _transformRoot (containing Child) //DiagnosticWriteLine(" _transformRoot.Arrange < " + finalRect); _transformRoot.Arrange(finalRect); //DiagnosticWriteLine(" Child.RenderSize = " + child.RenderSize); // This is the first opportunity under Silverlight to find out the Child's true DesiredSize if (IsSizeSmaller(finalSizeTransformed, child.RenderSize) && (Size.Empty == _childActualSize)) { // Unfortunately, all the work so far is invalid because the wrong DesiredSize was used //DiagnosticWriteLine(" finalSizeTransformed smaller than Child.RenderSize"); // Make a note of the actual DesiredSize _childActualSize = new Size(child.ActualWidth, child.ActualHeight); //DiagnosticWriteLine(" _childActualSize = " + _childActualSize); // Force a new measure/arrange pass InvalidateMeasure(); } else { // Clear the "need to measure/arrange again" flag _childActualSize = Size.Empty; } //DiagnosticWriteLine(" _transformRoot.RenderSize = " + _transformRoot.RenderSize); // Return result to perform the transformation //DiagnosticWriteLine("ArrangeOverride > " + finalSize); return finalSize; } /// <summary> /// Compute the largest usable size (greatest area) after applying the transformation to the specified bounds. /// </summary> /// <param name="arrangeBounds">Arrange bounds.</param> /// <returns>Largest Size possible.</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Closely corresponds to WPF's FrameworkElement.FindMaximalAreaLocalSpaceRect.")] private Size ComputeLargestTransformedSize(Size arrangeBounds) { //DiagnosticWriteLine(" ComputeLargestTransformedSize < " + arrangeBounds); // Computed largest transformed size Size computedSize = Size.Empty; // Detect infinite bounds and constrain the scenario bool infiniteWidth = double.IsInfinity(arrangeBounds.Width); if (infiniteWidth) { arrangeBounds.Width = arrangeBounds.Height; } bool infiniteHeight = double.IsInfinity(arrangeBounds.Height); if (infiniteHeight) { arrangeBounds.Height = arrangeBounds.Width; } // Capture the matrix parameters double a = _transformation.M11; double b = _transformation.M12; double c = _transformation.M21; double d = _transformation.M22; // Compute maximum possible transformed width/height based on starting width/height // These constraints define two lines in the positive x/y quadrant double maxWidthFromWidth = Math.Abs(arrangeBounds.Width / a); double maxHeightFromWidth = Math.Abs(arrangeBounds.Width / c); double maxWidthFromHeight = Math.Abs(arrangeBounds.Height / b); double maxHeightFromHeight = Math.Abs(arrangeBounds.Height / d); // The transformed width/height that maximize the area under each segment is its midpoint // At most one of the two midpoints will satisfy both constraints double idealWidthFromWidth = maxWidthFromWidth / 2; double idealHeightFromWidth = maxHeightFromWidth / 2; double idealWidthFromHeight = maxWidthFromHeight / 2; double idealHeightFromHeight = maxHeightFromHeight / 2; // Compute slope of both constraint lines double slopeFromWidth = -(maxHeightFromWidth / maxWidthFromWidth); double slopeFromHeight = -(maxHeightFromHeight / maxWidthFromHeight); if ((0 == arrangeBounds.Width) || (0 == arrangeBounds.Height)) { // Check for empty bounds computedSize = new Size(arrangeBounds.Width, arrangeBounds.Height); } else if (infiniteWidth && infiniteHeight) { // Check for completely unbound scenario computedSize = new Size(double.PositiveInfinity, double.PositiveInfinity); } else if (!MatrixHasInverse(_transformation)) { // Check for singular matrix computedSize = new Size(0, 0); } else if ((0 == b) || (0 == c)) { // Check for 0/180 degree special cases double maxHeight = (infiniteHeight ? double.PositiveInfinity : maxHeightFromHeight); double maxWidth = (infiniteWidth ? double.PositiveInfinity : maxWidthFromWidth); if ((0 == b) && (0 == c)) { // No constraints computedSize = new Size(maxWidth, maxHeight); } else if (0 == b) { // Constrained by width double computedHeight = Math.Min(idealHeightFromWidth, maxHeight); computedSize = new Size( maxWidth - Math.Abs((c * computedHeight) / a), computedHeight); } else if (0 == c) { // Constrained by height double computedWidth = Math.Min(idealWidthFromHeight, maxWidth); computedSize = new Size( computedWidth, maxHeight - Math.Abs((b * computedWidth) / d)); } } else if ((0 == a) || (0 == d)) { // Check for 90/270 degree special cases double maxWidth = (infiniteHeight ? double.PositiveInfinity : maxWidthFromHeight); double maxHeight = (infiniteWidth ? double.PositiveInfinity : maxHeightFromWidth); if ((0 == a) && (0 == d)) { // No constraints computedSize = new Size(maxWidth, maxHeight); } else if (0 == a) { // Constrained by width double computedHeight = Math.Min(idealHeightFromHeight, maxHeight); computedSize = new Size( maxWidth - Math.Abs((d * computedHeight) / b), computedHeight); } else if (0 == d) { // Constrained by height double computedWidth = Math.Min(idealWidthFromWidth, maxWidth); computedSize = new Size( computedWidth, maxHeight - Math.Abs((a * computedWidth) / c)); } } else if (idealHeightFromWidth <= ((slopeFromHeight * idealWidthFromWidth) + maxHeightFromHeight)) { // Check the width midpoint for viability (by being below the height constraint line) computedSize = new Size(idealWidthFromWidth, idealHeightFromWidth); } else if (idealHeightFromHeight <= ((slopeFromWidth * idealWidthFromHeight) + maxHeightFromWidth)) { // Check the height midpoint for viability (by being below the width constraint line) computedSize = new Size(idealWidthFromHeight, idealHeightFromHeight); } else { // Neither midpoint is viable; use the intersection of the two constraint lines instead // Compute width by setting heights equal (m1*x+c1=m2*x+c2) double computedWidth = (maxHeightFromHeight - maxHeightFromWidth) / (slopeFromWidth - slopeFromHeight); // Compute height from width constraint line (y=m*x+c; using height would give same result) computedSize = new Size( computedWidth, (slopeFromWidth * computedWidth) + maxHeightFromWidth); } // Return result //DiagnosticWriteLine(" ComputeLargestTransformedSize > " + computedSize); return computedSize; } /// <summary> /// Returns true if Size a is smaller than Size b in either dimension. /// </summary> /// <param name="a">Second Size.</param> /// <param name="b">First Size.</param> /// <returns>True if Size a is smaller than Size b in either dimension.</returns> private static bool IsSizeSmaller(Size a, Size b) { // WPF equivalent of following code: // return ((a.Width < b.Width) || (a.Height < b.Height)); return ((a.Width + AcceptableDelta < b.Width) || (a.Height + AcceptableDelta < b.Height)); } /// <summary> /// Rounds the non-offset elements of a Matrix to avoid issues due to floating point imprecision. /// </summary> /// <param name="matrix">Matrix to round.</param> /// <param name="decimals">Number of decimal places to round to.</param> /// <returns>Rounded Matrix.</returns> private static Matrix RoundMatrix(Matrix matrix, int decimals) { return new Matrix( Math.Round(matrix.M11, decimals), Math.Round(matrix.M12, decimals), Math.Round(matrix.M21, decimals), Math.Round(matrix.M22, decimals), matrix.OffsetX, matrix.OffsetY); } /// <summary> /// Implements WPF's Rect.Transform on Silverlight. /// </summary> /// <param name="rect">Rect to transform.</param> /// <param name="matrix">Matrix to transform with.</param> /// <returns>Bounding box of transformed Rect.</returns> private static Rect RectTransform(Rect rect, Matrix matrix) { // WPF equivalent of following code: // Rect rectTransformed = Rect.Transform(rect, matrix); Point leftTop = matrix.Transform(new Point(rect.Left, rect.Top)); Point rightTop = matrix.Transform(new Point(rect.Right, rect.Top)); Point leftBottom = matrix.Transform(new Point(rect.Left, rect.Bottom)); Point rightBottom = matrix.Transform(new Point(rect.Right, rect.Bottom)); double left = Math.Min(Math.Min(leftTop.X, rightTop.X), Math.Min(leftBottom.X, rightBottom.X)); double top = Math.Min(Math.Min(leftTop.Y, rightTop.Y), Math.Min(leftBottom.Y, rightBottom.Y)); double right = Math.Max(Math.Max(leftTop.X, rightTop.X), Math.Max(leftBottom.X, rightBottom.X)); double bottom = Math.Max(Math.Max(leftTop.Y, rightTop.Y), Math.Max(leftBottom.Y, rightBottom.Y)); Rect rectTransformed = new Rect(left, top, right - left, bottom - top); return rectTransformed; } /// <summary> /// Implements WPF's Matrix.Multiply on Silverlight. /// </summary> /// <param name="matrix1">First matrix.</param> /// <param name="matrix2">Second matrix.</param> /// <returns>Multiplication result.</returns> private static Matrix MatrixMultiply(Matrix matrix1, Matrix matrix2) { // WPF equivalent of following code: // return Matrix.Multiply(matrix1, matrix2); return new Matrix( (matrix1.M11 * matrix2.M11) + (matrix1.M12 * matrix2.M21), (matrix1.M11 * matrix2.M12) + (matrix1.M12 * matrix2.M22), (matrix1.M21 * matrix2.M11) + (matrix1.M22 * matrix2.M21), (matrix1.M21 * matrix2.M12) + (matrix1.M22 * matrix2.M22), ((matrix1.OffsetX * matrix2.M11) + (matrix1.OffsetY * matrix2.M21)) + matrix2.OffsetX, ((matrix1.OffsetX * matrix2.M12) + (matrix1.OffsetY * matrix2.M22)) + matrix2.OffsetY); } /// <summary> /// Implements WPF's Matrix.HasInverse on Silverlight. /// </summary> /// <param name="matrix">Matrix to check for inverse.</param> /// <returns>True if the Matrix has an inverse.</returns> private static bool MatrixHasInverse(Matrix matrix) { // WPF equivalent of following code: // return matrix.HasInverse; return (0 != ((matrix.M11 * matrix.M22) - (matrix.M12 * matrix.M21))); } } } 在 App.xaml 文件中 添加通用命名空间 xmlns:common="using:Common" 在 ApplicationResources 中创建新样式 <Application.Resources> <Style TargetType="common:LayoutTransformer"> <Setter Property="Foreground" Value="#FF000000"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="common:LayoutTransformer"> <Grid x:Name="TransformRoot" Background="{TemplateBinding Background}"> <ContentPresenter x:Name="Presenter" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Application.Resources> 现在将文本块逆时针旋转 90 度 添加通用命名空间 xmlns:common="using:Common" 并使用此代码 <common:LayoutTransformer> <common:LayoutTransformer.LayoutTransform> <RotateTransform Angle="-90" /> </common:LayoutTransformer.LayoutTransform> <TextBlock Text="CATEGORIES" FontSize="30"/> </common:LayoutTransformer> 如果旋转边框(父边框),TextBlock 也会旋转,因为它是边框的子边框。 <Border Height="80" Background="Teal"> <Border.RenderTransform> <RotateTransform Angle="-90" /> </Border.RenderTransform> <TextBlock Text="CATEGORIES" Foreground="White" FontFamily="Segoe UI Black" FontSize="30"> </TextBlock> </Border>

回答 2 投票 0

如何在运行时更改应用程序语言?

WinUI3的文档出奇的少,我什至找不到如何在应用程序运行时切换显示语言 回到问题,我创建了多种语言的资源文件,但是我...

回答 1 投票 0

在 c# UWP 应用程序中,当代码命中 await 关键字时,错误消息'value does not fall in the expected range'

我正在使用针对 .NET 7 的 WinUI 模板工作室。当代码在异步任务 <> 程序定义中遇到 await 关键字时,它会在 await 上抛出“值不在预期范围内”错误

回答 0 投票 0

更改自定义 WinUI3 按钮的背景颜色

我在我的 WinUI3 应用程序中创建了一个自定义按钮组件。下面给出了相同的代码。 我在我的 WinUI3 应用程序中创建了一个自定义按钮组件。下面给出了相同的代码。 <Button HorizontalAlignment="Center" VerticalAlignment="Center" Background="Transparent" BorderThickness="0" Width="{x:Bind Width}" Height="{x:Bind Height}"> <StackPanel Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center"> <FontIcon VerticalAlignment="Center" FontFamily="{StaticResource SymbolThemeFontFamily}" Glyph="{x:Bind Glyph}" FontSize="{x:Bind IconSize}" /> <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,10,0,0" Text="{x:Bind Label}" FontSize="{x:Bind FontSize}" /> </StackPanel> </Button> 默认情况下,它给出了一个非常浅的灰色背景,这在页面的白色背景中几乎不可见。所以我想在光标悬停在按钮上时或按钮通过选项卡处于焦点时更改按钮的背景颜色。 我怎样才能做到这一点? 我试过<ControlTemplate>,<VisualStateManager.VisualStateGroups><VisualState x:Name="PointerOver">和<Storybaord>但我无法让它工作。 我希望它有我选择的颜色,这样它更突出。就像默认的一样<AppBarButton> 正如您在 DefaultButtonStyle 中所见,VisualState PointerOver 将按钮的 Background 更改为名为 ButtonBackgroundPointerOver 的 ThemeResource。 (如果您不知道如何找到 generic.xaml,请查看此 answer。) 您可以像这样覆盖ButtonBackgroundPointerOver: <Button> <Button.Resources> <Button.Resources> <SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="HotPink" /> </Button.Resources> </Button.Resources> </Button> 不幸的是,Button 控件没有针对焦点事件的 VisualState。您可以做的是在代码隐藏中使用 Background 和 GotFocus 事件更改按钮的 LostFocus,但您也可以创建自定义控件: AwesomeButton.cs public class AwesomeButton : Button { public static readonly DependencyProperty FocusedBackgroundProperty = DependencyProperty.Register( nameof(FocusedBackground), typeof(Brush), typeof(AwesomeButton), new PropertyMetadata(default)); public AwesomeButton() { GotFocus += AwesomeButton_GotFocus; LostFocus += AwesomeButton_LostFocus; } public Brush FocusedBackground { get => (Brush)GetValue(FocusedBackgroundProperty); set => SetValue(FocusedBackgroundProperty, value); } private Brush? BackgroundBeforeGettingFocus { get; set; } private void AwesomeButton_GotFocus(object sender, RoutedEventArgs e) { BackgroundBeforeGettingFocus = Background; Background = FocusedBackground; } private void AwesomeButton_LostFocus(object sender, RoutedEventArgs e) { Background = BackgroundBeforeGettingFocus; } } 并像这样使用它: <local:AwesomeButton x:Name="AwesomeButton" Width="{x:Bind Width}" Height="{x:Bind Height}" HorizontalAlignment="Center" VerticalAlignment="Center" Background="Transparent" BorderThickness="0" FocusedBackground="LightGreen"> <Button.Resources> <SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="HotPink" /> </Button.Resources> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical"> <FontIcon VerticalAlignment="Center" FontFamily="{StaticResource SymbolThemeFontFamily}" FontSize="{x:Bind IconSize}" Glyph="{x:Bind Glyph}" /> <TextBlock Margin="0,10,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="{x:Bind FontSize}" Text="{x:Bind Label}" /> </StackPanel> </local:AwesomeButton>

回答 1 投票 0

分配访问模式下的 UWP 应用程序在 CTRL+ALT+DEL 后失去焦点

我有一个 UWP 应用程序在分配的访问权限(Kiosk 模式)下运行。当 PC 启动且用户登录时,应用程序以分配的访问权限启动,用户可以使用 TAB 按钮导航...

回答 0 投票 0

如何在 UWP 紧凑叠加模式下隐藏 tilebar

我的应用程序需要一个非常简单的用户界面,只有一个文本块和图像(基本上没有交互元素)。 所以我在 App.xaml.cs 中使用了以下代码来启动应用程序和激活应用程序方法。

回答 1 投票 0

在 UWP 中设置链接时 RichEditBox 的这种模棱两可的行为是什么

公共主页() { 这个.InitializeComponent(); box1 = new RichEditBox() { 宽度 = 500, 高度 = 500,

回答 0 投票 0

如何让 UWP 不聚焦,文本光标在外面?

我有一个具有手写功能的 UWP 应用程序,在带触摸屏的笔记本电脑上进行测试。 手写完成后,识别出的文字会暂时存储在一个文本块中。 然后我期望...

回答 1 投票 0

更改列标题背景 DataGrid UWP

我目前正在查看来自 Nuget Microsoft.Toolkit.Uwp.UI.Controls.DataGrid xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls" 的 UWP DataGrid,我想更改单个列

回答 3 投票 0

UWP WinUI2 Xaml:如何在禁用的 GridViewItem 上显示工具提示

我有以下Xaml 我有以下Xaml <DataTemplate x:Key="ImageTextTemplate" x:DataType="local1:CustomDataObject"> <Grid AutomationProperties.Name="{x:Bind Title}" Width="280"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Image Source="{x:Bind ImageLocation}" Height="100" Stretch="Fill" VerticalAlignment="Top"/> <StackPanel Grid.Column="1" Margin="8,0,0,8"> <TextBlock Text="{x:Bind Title}" Style="{ThemeResource SubtitleTextBlockStyle}" Margin="0,0,0,8"/> <StackPanel Orientation="Horizontal"> <TextBlock Text="{x:Bind Views}" Style="{ThemeResource CaptionTextBlockStyle}"/> <TextBlock Text=" Views " Style="{ThemeResource CaptionTextBlockStyle}"/> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="{x:Bind Likes}" Style="{ThemeResource CaptionTextBlockStyle}" /> <TextBlock Text=" Likes" Style="{ThemeResource CaptionTextBlockStyle}"/> </StackPanel> </StackPanel> </Grid> </DataTemplate> <GridView x:Name="ContentGridView" ContainerContentChanging="GridViewContainerContentChanging" IsItemClickEnabled="{x:Bind ItemClickCheckBox.IsChecked.Value, Mode=OneWay}" ItemClick="ContentGridView_ItemClick" ItemTemplate="{StaticResource ImageTemplate}" SelectionChanged="ContentGridView_SelectionChanged" FlowDirection="LeftToRight"/> 我使用处理程序禁用了一些项目ContainerContentChanging。我想在那些禁用的项目上设置工具提示。我该怎么做? 我尝试过的东西- 只需在处理程序中设置工具提示ContainerContentChanging。但似乎工具提示未显示在 UWP 应用程序中的禁用项目上。 试图处理PointerEntered的GridVewItem事件。但是一旦禁用网格项,就不会捕获任何指针事件。 好像ToolTipService.ShowOnDisabled不可用。它在 WPF 中可用。那么我们如何在 UWP 中显示禁用的 GridViewItem 上的工具提示? 我们如何在 UWP 中显示禁用的 GridViewItem 的工具提示? 你不能以正常的方式做到这一点。根据文档,当您禁用 GridViewItem 时,这意味着用户无法与 GridViewItem 进行交互,例如聚焦、按住或将指针悬停在上方。这些操作是触发工具提示的正常方式。 但是您可以尝试通过 ToolTip.IsOpen 属性 来做到这一点。如果要使用这种方式,需要手动控制tooltip打开和关闭的时间 我尝试在禁用的按钮中进行测试,您可以手动显示禁用按钮的工具提示。 Xaml: <StackPanel> <Button x:Name="TargetButton" Content="Submit" IsEnabled="False"> <ToolTipService.ToolTip> <ToolTip> <TextBlock Text="This is the tool tip"/> </ToolTip> </ToolTipService.ToolTip> </Button> <Button Content="Click" Click="Button_Click"/> </StackPanel> 代码: private void Button_Click(object sender, RoutedEventArgs e) { ToolTip tooltip = ToolTipService.GetToolTip(TargetButton) as ToolTip; tooltip.IsOpen = !tooltip.IsOpen; } 更多信息在这里:Control.IsEnabled Property 和ToolTip Class.

回答 1 投票 0

AccessDenied (System.UnauthorizedAccessException) 使用 VS2022 在设计器中打开 XAML 页面

我在 Visual Studio 2022 Pro 中创建了一个全新的测试 WinUI 2 项目。该项目只有标准样板类,没有添加/删除/更改任何内容。当我尝试打开 MainPage 时...

回答 0 投票 0

UWP C++WinRT 如何禁用 GridView 中的单个项目

我有一个 ,ItemsSource 绑定到 IObservableVector。我只想禁用此 GridView 中的几个项目。我怎样才能做到这一点?我看到其他类似的问题...

回答 1 投票 0

XAML 设计器在使用 UserControl 的子类时不加载

我创建了一个子类 MyUserControl,它扩展了内置的 UserControl 以在一些小部件之间共享一些公共字段和功能。然而,Visual Studio重启后,我发现所有的XAML ...

回答 0 投票 0

如何在 UWP 应用程序中自定义 toast 内容?

我正在为我的 UWP 应用程序干杯。我需要添加图像、文本和图标(都在同一行但不同的列中)。是否支持在 UWP 应用程序中向 toasts 添加图标?看着...

回答 1 投票 0

UWP 应用程序在启动时崩溃,但只有在安装应用程序后才会崩溃

我遇到了 UWP 应用程序在启动时崩溃的问题。它仅在应用程序安装后崩溃一次,通过 VS2019/2022 上的调试按钮或通过发布捆绑安装包。 ...

回答 1 投票 0

为什么此代码不填充我的 GridView 图像/如何将嵌套图像填充到 GridView?

我正在尝试用我的 C# 代码中的图像填充 GridView。 GridView 有一个包含网格的数据模板,其中有一个图像 - 对于上下文,我这样做是因为我想......

回答 0 投票 0

在 WinUI-3 中,如何在我的自定义工具提示类中获取父元素?

** 在我的 ScreenTipClass 中:** 在我的自定义 RibbonScreenTip 类中,我将事件处理为 ToolTip.Opened。 公共类 CustomToolTip:工具提示 { 公共 RibbonScreenTip () {

回答 1 投票 0

如何在我的自定义工具提示中获取父元素作为 RibbonScreenTip 类?

** 在我的 ScreenTipClass 中:** 在我的自定义 RibbonScreenTip 类中,我将事件处理为 ToolTip.Opened。 公共类 CustomToolTip:工具提示 { 公共 RibbonScreenTip () { 这.Ope...

回答 0 投票 0

任何人任何想法如何修复此 c# uwp 错误

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“无法将类型‘Windows.UI.Core.CoreWindow’转换为‘FireBrowser.Controls.BrowserEngines.ICoreWindowInterop’” '这是窗口代码' //

回答 0 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.