gpt4 book ai didi

wpf - 如何在 WPF TextBox 上为无效的依赖属性显示红色边框?

转载 作者:行者123 更新时间:2023-12-04 14:35:03 29 4
gpt4 key购买 nike

我有这个代码

using System.Windows;

namespace TestWpfApplication
{
public partial class Window5 : Window
{
public Window5()
{
InitializeComponent();
}
public int XX
{
get { return (int)GetValue(XXProperty); }
set { SetValue(XXProperty, value); }
}

public static readonly DependencyProperty XXProperty =
DependencyProperty.Register("XX", typeof(int), typeof(Window5), new PropertyMetadata(1),ValidateXX);

private static bool ValidateXX(object value)
{
int? d =value as int?;
var res= d != null && d > 0 && d < 20;
return res;
}
}
}

而这个 XAML
<Window x:Class="TestWpfApplication.Window5"
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:TestWpfApplication"
mc:Ignorable="d"
Title="Window5" Height="300" Width="300">

<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="22" Margin="120,68,0,0" TextWrapping="Wrap" Text="{Binding XX, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Window5}}, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="22" Margin="96,122,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
</Grid>

我喜欢在 TextBox 中输入无效值时显示红色边框..
ValidateXX 方法,工作正常但是TextBox Border 中没有出现红色Border。

最佳答案

更新您的绑定(bind)以添加“ValidatesOnExceptions=True”属性。

更新为:

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="22" Margin="120,68,0,0" TextWrapping="Wrap" Text="{Binding XX, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Window5}}, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}" VerticalAlignment="Top" Width="120"/>

关于wpf - 如何在 WPF TextBox 上为无效的依赖属性显示红色边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41199291/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com