我在 WPF 中创建了一个简单的 spinbox(numericUpDown) 控件(因为没有)。
我已经创建了一个自定义值属性,我想使用模型创建一个数据绑定。
<UserControl x:Class="PmFrameGrabber.Views.SpinBox"
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:PmFrameGrabber.Views"
mc:Ignorable="d"
d:DesignHeight="25" d:DesignWidth="100">
<UserControl.Resources>
<local:IntToStringConv x:Key="IntToStringConverter" />
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="25" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Name="TbValue" Grid.RowSpan="2" HorizontalContentAlignment="Right"
VerticalContentAlignment="Center" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Text="{Binding Value, Converter={StaticResource IntToStringConverter}}"/>
<Button Name="BtPlus" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch" Margin="3,0,0,0"
VerticalAlignment="Center" FontSize="8" Content="+" Click="BtPlus_Click" />
<Button Name="BtMinus" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch" Margin="3,0,0,0"
VerticalAlignment="Center" FontSize="8" Content="-" Click="BtMinus_Click" />
</Grid>
</UserControl>
这是后面的代码:
public partial class SpinBox : UserControl
{
public static DependencyProperty ValueDP =
DependencyProperty.Register("Value", typeof(int), typeof(SpinBox), new UIPropertyMetadata(0));
// Public bindable properties
public int Value
{
get => (int)GetValue(ValueDP);
set => SetValue(ValueDP, value);
}
public SpinBox()
{
InitializeComponent();
DataContext = this;
}
private void BtPlus_Click(object sender, RoutedEventArgs e) => Value++;
private void BtMinus_Click(object sender, RoutedEventArgs e) => Value--;
}
在另一个视图中,我试图使用这样的控件:
<local:SpinBox Width="80" Height="25" Value="{Binding Cam.ExposureTime, Mode=TwoWay}" />
在这里我得到一个错误: Wpf binding can only be set on a dependencyproperty of an dependencyobject
模型属性在 C++/CLI 中是这样写的:
property int ExposureTime
{
void set(int value)
{
m_settings->exposureTime = value;
OnPropertyChanged(GetPropName(Camera, ExposureTime));
}
int get()
{
return m_settings->exposureTime;
}
}
使用此属性绑定适用于其他控件(文本框、标签)。
我想问题出在我的自定义 SpinBox 和我创建 Value 属性的方式上。经过一天的网络挖掘后,我还没有找到其他可以做的事情。