[英]Bind a property in xaml template to viewmodel (RibbonTextBox)
更大问题的背景信息我想解决的问题是允许用户在RibbonTextBox控件模板中设置标签的MinWidth。 一旦我弄清楚第一个属性,我打算与其他属性一样。 这样做的目的是通过设置宽度来对齐堆叠在彼此顶部的RibbonTextBox。 到目前为止,我通过硬编码控件模板中的值来解决我的问题。 我想使这个控件可重用,因此需要能够设置一些绑定。
需要解决的问题我有以下xaml(为了便于阅读,已删除了大量xaml)。 在这个xaml的中心,你可以看到一个标签。 该标签有一个MinWidth
属性,这是我的问题的焦点。
<DataTemplate x:Uid="DataTemplate_0" DataType="{x:Type element:RibbonTextBoxVM}">
<ribbon:RibbonTextBox x:Uid="ribbon:RibbonTextBox_1" IsReadOnly="{Binding IsReadOnly}" Text="{Binding Text}" Label="{Binding Label}" >
<ribbon:RibbonTextBox.Style>
<Style TargetType="{x:Type ribbon:RibbonTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ribbon:RibbonTextBox}">
<StackPanel Orientation="Horizontal">
<Label Margin='2,0,0,0' Padding='0,0,0,5' BorderThickness='0,0,0,0' HorizontalAlignment='Stretch' VerticalAlignment='Bottom'
HorizontalContentAlignment='Left' VerticalContentAlignment='Top' Background='#00FFFFFF' FlowDirection='LeftToRight'
Visibility='Visible' MinWidth="80">
<!--other stuff-->
</Label>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ribbon:RibbonTextBox.Style>
</ribbon:RibbonTextBox>
</DataTemplate>
以下是支持上述xaml的视图模型。
public class RibbonTextBoxVM : ViewModel
{
public string Label
{
get { return GetValue(Properties.Label); }
set { SetValue(Properties.Label, value); }
}
public string Text
{
get { return GetValue(Properties.Text); }
set { SetValue(Properties.Text, value); }
}
public bool IsReadOnly
{
get { return GetValue(Properties.IsReadOnly); }
set { SetValue(Properties.IsReadOnly, value); }
}
public RibbonTextBoxVM(string text, string label, bool isReadOnly)
{
Text = text;
Label = label;
IsReadOnly = isReadOnly;
}
}
我想要做的是拥有一个属性LabelMinWidth。
public double LabelMinWidth
{
get { return GetValue(Properties.LabelMinWidth); }
set { SetValue(Properties.LabelMinWidth, value); }
}
我想允许用户将值传递给构造函数来设置该属性。 这是容易的部分。
我无法弄清楚的部分是如何将我的新LabelMinWidth绑定到xaml中控件模板内标签的MinWidth属性。
如果有人能指出我正确的方向,那将是伟大的。 我很乐意回答有关该问题的任何问题。
由于您的RibbonTextBox
将您的VM作为其DataContext
,因此您可以在ControlTemplate
使用Binding
,就像绑定其他属性一样:
<Label ... MinWidth="{Binding LabelMinWidth}">
这是有效的,因为在WPF中, DataContext
继承所有子项(除非被重写)。 因此,如果您希望在模板中的控件中绑定到VM上的属性,则只需绑定它即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.