我有以下 UserControl,它是一個帶有標簽的預先格式化的 TextBox:
XAML:
<UserControl
x:Class="Aerloc.Components.LabeledTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Aerloc.Components"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox Text="{x:Bind Caption, Mode=TwoWay}" Style="{StaticResource LabelTextBox}" Grid.Column="0"/>
<TextBox Text="{x:Bind Value, Mode=TwoWay}" IsEnabled="{x:Bind IsEditable, Mode=OneWay}" Style="{StaticResource FieldTextBox}" Grid.Column=1/>
</Grid>
</UserControl>
代碼背后:
public sealed partial class LabeledTextBox : UserControl
{
public DependencyProperty CaptionProperty = DependencyProperty.Register(nameof(Value), typeof(string), typeof(LabeledTextBox), new PropertyMetadata(null));
public DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Caption), typeof(string), typeof(LabeledTextBox), new PropertyMetadata(null));
public DependencyProperty IsEditableProperty = DependencyProperty.Register(nameof(IsEditable), typeof(bool), typeof(LabeledTextBox), new PropertyMetadata(null));
public string Caption
{
get => (string)GetValue(CaptionProperty);
set => SetValue(CaptionProperty, value);
}
public string Value
{
get => (string)GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
public bool IsEditable
{
get => (bool)GetValue(IsEditableProperty);
set => SetValue(IsEditableProperty, value);
}
public LabeledTextBox()
{
this.InitializeComponent();
}
}
我在使用雙向系結傳遞給 UserControl 的值時遇到問題。當我創建系結(下面的代碼)時,我收到一條錯誤訊息,提示“TwoWay 系結目標'值'必須是依賴屬性”。如何通過兩種方式將 UserControl 中的值系結到 ViewModel?
<components:LabeledTextBox
Caption="First Name:"
Value="{x:Bind ViewModel.SelectedUser.FirstName, Mode=TwoWay}"
IsEditable="{x:Bind ViewModel.IsAddEditModeEnabled}"/>
uj5u.com熱心網友回復:
DependencyProperty需要static readonly。您的 DependencyProperties 名稱也有誤。
解決這個問題,
public DependencyProperty CaptionProperty =
DependencyProperty.Register(
nameof(Value),
typeof(string),
typeof(LabeledTextBox),
new PropertyMetadata(null));
public DependencyProperty ValueProperty =
DependencyProperty.Register(
nameof(Caption),
typeof(string),
typeof(LabeledTextBox),
new PropertyMetadata(null));
對此,
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register(
nameof(Caption),
typeof(string),
typeof(LabeledTextBox),
new PropertyMetadata(null));
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(
nameof(Value),
typeof(string),
typeof(LabeledTextBox),
new PropertyMetadata(null));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511400.html
