- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个用于 Ip 地址的 TextBoxInputMaskBehavior,如下所示:
和 xaml 代码:
<UserControl x:Class="Customizing.Views.IpRangeFields"
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:ig="http://schemas.infragistics.com/xaml"
xmlns:local="clr-namespace:Customizing.Views"
xmlns:net="clr-namespace:System.Net;assembly=System"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:behaviors="clr-namespace:Customizing.Behaviors"
xmlns:system="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
x:Name="Uc"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<system:String x:Key="InputMaskIp">000.000.000.000</system:String>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="10" />
<RowDefinition Height="60" />
<RowDefinition Height="10" />
<RowDefinition Height="60" />
<RowDefinition Height="10" />
<RowDefinition Height="60" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2.5*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Start" VerticalContentAlignment="Center" FontSize="18"
HorizontalContentAlignment="Center" FontWeight="Bold" />
<Label Grid.Row="2" Grid.Column="0" Content="End" VerticalContentAlignment="Center" FontSize="18"
HorizontalContentAlignment="Center" FontWeight="Bold" />
<Label Grid.Row="4" Grid.Column="0" Content="Subnet" VerticalContentAlignment="Center" FontSize="18"
HorizontalContentAlignment="Center" FontWeight="Bold" />
<Label Grid.Row="6" Grid.Column="0" Content="Gateway" VerticalContentAlignment="Center" FontSize="18"
HorizontalContentAlignment="Center" FontWeight="Bold" />
<TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="0" Grid.Column="1"
FontSize="22" Validation.Error="_ValidationError">
<TextBox.Text>
<Binding ElementName="Uc" Path="Start" ValidatesOnNotifyDataErrors="True"
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="true">
<Binding.ValidationRules>
<local:IpAddressRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<i:Interaction.Behaviors>
<behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
</i:Interaction.Behaviors>
</TextBox>
<TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="2" Grid.Column="1"
FontSize="22" Validation.Error="_ValidationError">
<Binding ElementName="Uc" Path="End" ValidatesOnNotifyDataErrors="True"
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="true">
<Binding.ValidationRules>
<local:IpAddressRule />
</Binding.ValidationRules>
</Binding>
<i:Interaction.Behaviors>
<behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
</i:Interaction.Behaviors>
</TextBox>
<TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="4" Grid.Column="1"
FontSize="22" Validation.Error="_ValidationError">
<TextBox.Text>
<Binding ElementName="Uc" Path="Subnet" ValidatesOnNotifyDataErrors="True"
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="true">
<Binding.ValidationRules>
<local:IpAddressRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<i:Interaction.Behaviors>
<behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
</i:Interaction.Behaviors>
</TextBox>
<TextBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Row="6" Grid.Column="1"
FontSize="22" Validation.Error="_ValidationError">
<TextBox.Text>
<Binding ElementName="Uc" Path="Gateway" ValidatesOnNotifyDataErrors="True"
UpdateSourceTrigger="PropertyChanged"
NotifyOnValidationError="true">
<Binding.ValidationRules>
<local:IpAddressRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<i:Interaction.Behaviors>
<behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
</i:Interaction.Behaviors>
</TextBox>
</Grid>
</UserControl>
以及背后的代码:
using System.Globalization;
using System.Net;
using System.Windows;
using System.Windows.Controls;
namespace Customizing.Views
{
/// <summary>
/// Interaction logic for IpRangeFields.xaml
/// </summary>
public partial class IpRangeFields : UserControl
{
public static readonly DependencyProperty StartProperty = DependencyProperty.Register("Start", typeof (string),
typeof (IpRangeFields), new PropertyMetadata(null));
public static readonly DependencyProperty EndProperty = DependencyProperty.Register("End", typeof (string),
typeof (IpRangeFields), new PropertyMetadata(null));
public static readonly DependencyProperty SubnetProperty = DependencyProperty.Register("Subnet", typeof (string),
typeof (IpRangeFields), new PropertyMetadata(null));
public static readonly DependencyProperty GatewayProperty = DependencyProperty.Register("Gateway",
typeof (string),
typeof (IpRangeFields), new PropertyMetadata(null));
// Register the routed event
public static readonly RoutedEvent ErrorEvent =
EventManager.RegisterRoutedEvent("Error", RoutingStrategy.Bubble,
typeof (RoutedEventHandler), typeof (IpRangeFields));
public IpRangeFields()
{
InitializeComponent();
}
public string Start
{
get { return (string) GetValue(StartProperty); }
set { SetValue(StartProperty, value); }
}
public string End
{
get { return (string) GetValue(EndProperty); }
set { SetValue(EndProperty, value); }
}
public string Subnet
{
get { return (string) GetValue(SubnetProperty); }
set { SetValue(SubnetProperty, value); }
}
public string Gateway
{
get { return (string) GetValue(GatewayProperty); }
set { SetValue(GatewayProperty, value); }
}
public event RoutedEventHandler Error
{
add { AddHandler(ErrorEvent, value); }
remove { RemoveHandler(ErrorEvent, value); }
}
private void _ValidationError(object sender, ValidationErrorEventArgs e)
{
RaiseEvent(new RoutedEventArgs(ErrorEvent, sender));
}
}
public class IpAddressRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
IPAddress ip;
if (!IPAddress.TryParse(value.ToString(), out ip))
{
return new ValidationResult(false, "IP address is not valid.");
}
return new ValidationResult(true, null);
}
}
}
我的问题是,正如您在图片中看到的,只有子网字段显示值,而其他三个字段没有。我敢肯定,
<behaviors:TextBoxInputMaskBehavior InputMask="{StaticResource InputMaskIp}" PromptChar="0" />
遮盖了三个字段的值,因此看不到值。
令我困惑的是,为什么会出现 subnet 字段的值?我在其他三个字段上做错了什么?
文本框掩码类:
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace Customizing.Behaviors
{
/// <summary>
/// InputMask for Textbox with 2 Properties: <see cref="InputMask" />, <see cref="PromptChar" />.
/// </summary>
public class TextBoxInputMaskBehavior : Behavior<TextBox>
{
public MaskedTextProvider Provider { get; private set; }
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObjectLoaded;
AssociatedObject.PreviewTextInput += AssociatedObjectPreviewTextInput;
AssociatedObject.PreviewKeyDown += AssociatedObjectPreviewKeyDown;
DataObject.AddPastingHandler(AssociatedObject, Pasting);
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= AssociatedObjectLoaded;
AssociatedObject.PreviewTextInput -= AssociatedObjectPreviewTextInput;
AssociatedObject.PreviewKeyDown -= AssociatedObjectPreviewKeyDown;
DataObject.RemovePastingHandler(AssociatedObject, Pasting);
}
/*
Mask Character Accepts Required?
0 Digit (0-9) Required
9 Digit (0-9) or space Optional
# Digit (0-9) or space Required
L Letter (a-z, A-Z) Required
? Letter (a-z, A-Z) Optional
& Any character Required
C Any character Optional
A Alphanumeric (0-9, a-z, A-Z) Required
a Alphanumeric (0-9, a-z, A-Z) Optional
Space separator Required
. Decimal separator Required
, Group (thousands) separator Required
: Time separator Required
/ Date separator Required
$ Currency symbol Required
In addition, the following characters have special meaning:
Mask Character Meaning
< All subsequent characters are converted to lower case
> All subsequent characters are converted to upper case
| Terminates a previous < or >
\ Escape: treat the next character in the mask as literal text rather than a mask symbol
*/
private void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
{
Provider = new MaskedTextProvider(InputMask, CultureInfo.CurrentCulture);
Provider.Set(AssociatedObject.Text);
Provider.PromptChar = PromptChar;
AssociatedObject.Text = Provider.ToDisplayString();
//seems the only way that the text is formatted correct, when source is updated
var textProp = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof (TextBox));
if (textProp != null)
{
textProp.AddValueChanged(AssociatedObject, (s, args) => UpdateText());
}
}
private void AssociatedObjectPreviewTextInput(object sender, TextCompositionEventArgs e)
{
TreatSelectedText();
var position = GetNextCharacterPosition(AssociatedObject.SelectionStart);
if (Keyboard.IsKeyToggled(Key.Insert))
{
if (Provider.Replace(e.Text, position))
position++;
}
else
{
if (Provider.InsertAt(e.Text, position))
position++;
}
position = GetNextCharacterPosition(position);
RefreshText(position);
e.Handled = true;
}
private void AssociatedObjectPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space) //handle the space
{
TreatSelectedText();
var position = GetNextCharacterPosition(AssociatedObject.SelectionStart);
if (Provider.InsertAt(" ", position))
RefreshText(position);
e.Handled = true;
}
if (e.Key == Key.Back) //handle the back space
{
if (TreatSelectedText())
{
RefreshText(AssociatedObject.SelectionStart);
}
else
{
if (AssociatedObject.SelectionStart != 0)
{
if (Provider.RemoveAt(AssociatedObject.SelectionStart - 1))
RefreshText(AssociatedObject.SelectionStart - 1);
}
}
e.Handled = true;
}
if (e.Key == Key.Delete) //handle the delete key
{
//treat selected text
if (TreatSelectedText())
{
RefreshText(AssociatedObject.SelectionStart);
}
else
{
if (Provider.RemoveAt(AssociatedObject.SelectionStart))
RefreshText(AssociatedObject.SelectionStart);
}
e.Handled = true;
}
}
/// <summary>
/// Pasting prüft ob korrekte Daten reingepastet werden
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof (string)))
{
var pastedText = (string) e.DataObject.GetData(typeof (string));
TreatSelectedText();
var position = GetNextCharacterPosition(AssociatedObject.SelectionStart);
if (Provider.InsertAt(pastedText, position))
{
RefreshText(position);
}
}
e.CancelCommand();
}
private void UpdateText()
{
//check Provider.Text + TextBox.Text
if (Provider.ToDisplayString().Equals(AssociatedObject.Text))
return;
//use provider to format
var success = Provider.Set(AssociatedObject.Text);
//ui and mvvm/codebehind should be in sync
SetText(success ? Provider.ToDisplayString() : AssociatedObject.Text);
}
/// <summary>
/// Falls eine Textauswahl vorliegt wird diese entsprechend behandelt.
/// </summary>
/// <returns>true Textauswahl behandelt wurde, ansonsten falls </returns>
private bool TreatSelectedText()
{
if (AssociatedObject.SelectionLength > 0)
{
return Provider.RemoveAt(AssociatedObject.SelectionStart,
AssociatedObject.SelectionStart + AssociatedObject.SelectionLength - 1);
}
return false;
}
private void RefreshText(int position)
{
SetText(Provider.ToDisplayString());
AssociatedObject.SelectionStart = position;
}
private void SetText(string text)
{
AssociatedObject.Text = string.IsNullOrWhiteSpace(text) ? string.Empty : text;
}
private int GetNextCharacterPosition(int startPosition)
{
var position = Provider.FindEditPositionFrom(startPosition, true);
if (position == -1)
return startPosition;
return position;
}
#region DependencyProperties
public static readonly DependencyProperty InputMaskProperty =
DependencyProperty.Register("InputMask", typeof (string), typeof (TextBoxInputMaskBehavior), null);
public string InputMask
{
get { return (string) GetValue(InputMaskProperty); }
set { SetValue(InputMaskProperty, value); }
}
public static readonly DependencyProperty PromptCharProperty =
DependencyProperty.Register("PromptChar", typeof (char), typeof (TextBoxInputMaskBehavior),
new PropertyMetadata('_'));
public char PromptChar
{
get { return (char) GetValue(PromptCharProperty); }
set { SetValue(PromptCharProperty, value); }
}
#endregion
}
}
最佳答案
我复制了你的代码,它运行没有错误。
设置值(ipRange 由您控制):
ipRange.Start = "123.456.789.000";
ipRange.End = "123.456.789.000";
ipRange.Subnet = "123.456.789.000";
ipRange.Gateway = "123.456.789.000";
结果:
我认为,绑定(bind)问题或其他问题,但无法控制。
一条评论。将掩码从 000.000.000.000
更改为 000\.000\.000\.000
因为 .
是小数点分隔符(在我的国家/地区是逗号,而不是点,因此您可能会在文化支持方面遇到麻烦。
关于c# - TextBoxInputMaskBehavior 覆盖值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30567155/
我的问题:非常具体。我正在尝试想出解析以下文本的最简单方法: ^^domain=domain_value^^version=version_value^^account_type=account_ty
好吧,这就是我的困境: 我正在为 Reddit 子版 block 开发常见问题解答机器人。我在 bool 逻辑方面遇到了麻烦,需要一双更有经验的眼睛(这是我在 Python 中的第一次冒险)。现在,该
它首先遍历所有 y 值,然后遍历所有 x 值。我需要 X 和 y 同时改变。 For x = 3 To lr + 1 For y = 2 To lr anyl.Cells(x, 1)
假设我有一个包含 2 列的 Excel 表格:单元格 A1 到 A10 中的日期和 B1 到 B10 中的值。 我想对五月日期的所有值求和。我有3种可能性: {=SUM((MONTH(A1:A10)=
如何转换 Z-score来自 Z-distribution (standard normal distribution, Gaussian distribution)到 p-value ?我还没有找到
我正在重写一些 Javascript 代码以在 Excel VBA 中工作。由于在这个网站上搜索,我已经设法翻译了几乎所有的 Javascript 代码!但是,有些代码我无法准确理解它在做什么。这是一
我遇到过包含日期格式的时间戳日期的情况。然后我想构建一个图表,显示“点击”项目的数量“每天”, //array declaration $array1 = array("Date" => 0); $a
我是scala的新手! 我的问题是,是否有包含成员的案例类 myItem:Option[String] 当我构造类时,我需要将字符串内容包装在: Option("some string") 要么 So
我正在用 PHP 创建一个登录系统。我需要用户使用他或她的用户名或电子邮件或电话号码登录然后使用密码。因为我知道在 Java 中我们会像 email==user^ username == user 这
我在 C++ 项目上使用 sqlite,但是当我在具有文本值的列上使用 WHERE 时出现问题 我创建了一个 sqlite 数据库: CREATE TABLE User( id INTEGER
当构造函数是显式时,它不用于隐式转换。在给定的代码片段中,构造函数被标记为 explicit。那为什么在 foo obj1(10.25); 情况下它可以工作,而在 foo obj2=10.25; 情况
我知道这是一个主观问题,所以如果需要关闭它,我深表歉意,但我觉得它经常出现,让我想知道是否普遍偏爱一种形式而不是另一种形式。 显然,最好的答案是“重构代码,这样你就不需要测试是否存在错误”,但有时没有
这两个 jQuery 选择器有什么区别? 以下是来自 w3schools.com 的定义: [attribute~=value] 选择器选择带有特定属性,其值包含特定字符串。 [attribute*=
为什么我们需要CSS [attribute|=value] Selector根本当 CSS3 [attribute*=value] Selector基本上完成相同的事情,浏览器兼容性几乎相似?是否存在
我正在解决 regx 问题。我已经有一个像这样的 regx [0-9]*([.][0-9]{2})。这是 amont 格式验证。现在,通过此验证,我想包括不应提供 0 金额。比如 10 是有效的,但
我正在研究计算机科学 A 考试的样题,但无法弄清楚为什么以下问题的正确答案是正确的。 考虑以下方法。 public static void mystery(List nums) { for (
好的,我正在编写一个 Perl 程序,它有一个我收集的值的哈希值(完全在一个完全独立的程序中)并提供给这个 Perl 脚本。这个散列是 (string,string) 的散列。 我想通过 3 种方式对
我有一个表数据如下,来自不同的表。仅当第三列具有值“债务”并且第一列(日期)具有最大值时,我才想从第四列中获取最大值。最终值基于 MAX(DATE) 而不是 MAX(PRICE)。所以用简单的语言来说
我有一个奇怪的情况,只有错误状态保存到数据库中。当“状态”应该为 true 时,我的查询仍然执行 false。 我有具有此功能的 Controller public function change_a
我有一个交易表(针对所需列进行了简化): id client_id value 1 1 200 2 2 150 3 1
我是一名优秀的程序员,十分优秀!