更大问题的背景信息 我要解决的问题是允许用户在 RibbonTextBox 控件模板内设置标签的 MinWidth。一旦我弄清楚第一个属性,我打算与其他属性相同。这样做的目的是能够通过设置宽度对齐堆叠在彼此顶部的 RibbonTextBox。到目前为止,我通过对控件模板中的值进行硬编码解决了我的问题。我想让这个控件可重用,因此需要能够设置一些绑定(bind)。
需要解决的问题
我有以下 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 的 View 模型。
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 绑定(bind)到 xaml 中控件模板内标签的 MinWidth 属性。
如果有人能给我指出正确的方向,那就太好了。我很乐意回答有关该问题的任何问题。
最佳答案
由于您的 RibbonTextBox
将您的 VM 作为其 DataContext
,您可以在 ControlTemplate
中使用 Binding
>,就像绑定(bind)其他属性一样:
<Label ... MinWidth="{Binding LabelMinWidth}">
这是有效的,因为在 WPF 中,DataContext
继承给所有子级(除非被覆盖)。因此,如果您在 VM 上有一个属性想要绑定(bind)到模板的控件中,您只需绑定(bind)到它即可。
关于c# - 将 xaml 模板中的属性绑定(bind)到 viewmodel (RibbonTextBox),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18150833/