将xaml模板中的属性绑定到视图模型(RibbonTextBox)

本文关键字:视图 模型 RibbonTextBox 绑定 属性 xaml | 更新日期: 2023-09-27 18:26:58

较大问题的背景信息我试图解决的问题是允许用户在RibbonTextBox控件模板内设置标签的最小宽度。一旦我能找到第一个,我打算对其他房产也这样做。这样做的目的是能够通过设置宽度来对齐堆叠在一起的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属性。

如果有人能给我指明正确的方向,那就太好了。我很乐意回答有关这个问题的任何问题。

将xaml模板中的属性绑定到视图模型(RibbonTextBox)

由于您的In your RibbonTextBox将您的VM作为其DataContext,因此您可以在ControlTemplate中使用Binding,就像您绑定其他属性一样:

<Label ... MinWidth="{Binding LabelMinWidth}">

这是因为在WPF中,DataContext继承到所有子级(除非被重写)。因此,如果您在VM上有一个属性,您想在模板中的控件中绑定到该属性,则只需绑定到它即可。