我制作了一个箭头控制器来递减 TextBox 中的数值:
<Label Content="{Binding ElementName=qqq, Path=Text}" />
<ctrls:UpDownCtrl x:Name="qqq" />
构造函数中断:
UpDownCtrl.xaml:
<UserControl x:Class="prod_bw.Ctrls.UpDownCtrl"
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:prod_bw.Ctrls"
mc:Ignorable="d" d:DesignWidth="800" Height="22">
<UserControl.DataContext>
<local:UpDownCtrl />
</UserControl.DataContext>
<StackPanel Orientation="Horizontal" Height="22">
<TextBox x:Name="value" Text="{Binding Text}" Width="32" PreviewTextInput="value_PreviewTextInput" DataObject.Pasting="value_Pasting" MaxLength="3" />
<StackPanel>
<Button Height="11" Width="13">
<TextBlock FontFamily="Marlett" FontSize="11" Text="5" HorizontalAlignment="Center" VerticalAlignment="Center" Cursor="Hand" />
</Button>
<Button Height="11" Width="13">
<TextBlock FontFamily="Marlett" FontSize="11" Text="6" HorizontalAlignment="Center" VerticalAlignment="Center" Cursor="Hand" />
</Button>
</StackPanel>
</StackPanel>
</UserControl>
UpDownCtrl.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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;
using static System.Net.Mime.MediaTypeNames;
namespace prod_bw.Ctrls
{
/// <summary>
/// Логика взаимодействия для UpDownCtrl.xaml
/// </summary>
public partial class UpDownCtrl : UserControl
{
private static readonly Regex onlyNumberRegex = new Regex("[^0-9]");
public string Text { get; set; }
public UpDownCtrl()
{
InitializeComponent();
}
private void value_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = onlyNumberRegex.IsMatch(e.Text);
}
private void value_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
string text = (string)e.DataObject.GetData(typeof(string));
if (onlyNumberRegex.IsMatch(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
}
}


呈现 XAML 实例化类
UpDownCtrl也就是说,它调用它的构造函数
并且构造函数依次调用 XAML 渲染
以此类推,直到弹出
StackOverflowException要决定,就在这里
必须删除
构造函数这样改变
为了让提示按上下文在 XAML 中,您需要将其添加到控件的属性中
但一般情况下
DataContext,控件通常不会设置,也不会以任何方式使用。对于控件中的绑定,而不是 INPC 属性,请使用DependencyProperty.TemplateBinding可以通过fromControlTemplate- an example附加到它。然后,在父窗口的可视化树中创建用户控件时,可以为其设置必要的属性并控制其逻辑。并且可以通过通常的事件处理程序和内部逻辑来操作用户控件的私有数据。
在用户控件内部,不一定要安排MVVM,很多时候只需要View就够了。并且所有 DP 数据绑定都是以通常的方式在外部进行的,就像您对任何其他标准控件所做的那样。