更大问题的背景信息 我试图解决的问题是允许用户在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属性。
如果有人能指出我正确的方向那将是伟大的。我很乐意回答有关此问题的任何问题。
答案 0 :(得分:4)
由于您的RibbonTextBox
将您的虚拟机设为DataContext
,因此您可以在Binding
中使用ControlTemplate
,就像绑定其他媒体资源一样:
<Label ... MinWidth="{Binding LabelMinWidth}">
这是有效的,因为在WPF中,DataContext
继承所有子节点(除非被覆盖)。因此,如果您的VM上有一个要绑定到模板中的控件的属性,则只需绑定它即可。