Friday, 9 August 2013

Bind a property in xaml template to viewmodel (RibbonTextBox)

Bind a property in xaml template to viewmodel (RibbonTextBox)

Background info of larger problem The problem I am trying to solve is to
allow a user to set the MinWidth of the label inside of the RibbonTextBox
control template. I intend to the same with other properties once I can
figure out the first one. The aim of this is to be able to align
RibbonTextBoxes stacked on top of each other by setting widths. I am so
far solved my problem by hardcoding the values in the control template. I
would like to make this control reusable and thus need to be able to set
up some binding.
The problem that needs solving I have the following xaml (lots of xaml has
been removed for readability). At the centre of this xaml you can see a
label. That label has a MinWidth property which is the focus of my
question.
<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>
The following is the viewmodel that backs the above 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;
}
}
What I would like to do is have a property LabelMinWidth.
public double LabelMinWidth
{
get { return GetValue(Properties.LabelMinWidth); }
set { SetValue(Properties.LabelMinWidth, value); }
}
I want to allow the user to pass in a value to the constructor to set that
property. That is the easy part.
The part I cannot figure out is how to bind my new LabelMinWidth to the
MinWidth property of the label inside the control template in the xaml.
If anyone can point me in the right direction that would be great. Ill be
happy to answer any questions about the problem.

No comments:

Post a Comment