我有自己的 UserControl,aLabeledTextBox
是 aLabel
和 a..well,的组合TextBox
。此控件有两个属性:Caption
将绑定到 的标题Label
,以及Value
将绑定到Text
的TextBox
。
代码:
public class LabeledTextBox : Control
{
static LabeledTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(LabeledTextBox), new FrameworkPropertyMetadata(typeof(LabeledTextBox)));
}
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
// Using a DependencyProperty as the backing store for Caption. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Caption", typeof(string), typeof(LabeledTextBox), new UIPropertyMetadata(""));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(LabeledTextBox), new UIPropertyMetadata(""));
}
XAML:
<Style TargetType="{x:Type local:LabeledTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:LabeledTextBox}">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="{TemplateBinding Caption}" />
<TextBox Name="Box" Margin="3,0,3,3" Grid.Row="1" Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
用法:
<uc:LabeledTextBox Caption="Code:" Value="{Binding ExpenseCode}" />
最初我以为我在这里找到了答案:WPF TemplateBinding vs RelativeSource TemplatedParent
TemplateBinding
这详细说明了和之间的区别RelativeSource TemplatedParent
。我已经相应地更改了我的代码,但仍然感觉我错过了一步。OneWay 绑定确实有效,我的文本框绑定到 Value 属性,但更改不会注册。
我怎样才能让它工作?