0
我在WPF中創建了一個簡單的spinbox(numericUpDown)控件(因爲沒有)。如何使用自定義屬性設置數據綁定
我已經創建了一個自定義的Value屬性,我想用Model創建一個數據綁定。
<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綁定只能設置在依賴對象的依賴屬性上
模型屬性是在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屬性的方式。在挖掘網絡的一天之後,我還沒有發現還有什麼要做。
非常感謝,您的點解決所有的問題。 – Safiron