Reputation: 587
I have two text boxes detailing the position of something on a canvas, only I want the values in the text boxes to be a number in the range 0 to 1 representing a percentage of the width/height.
I need to some how convert that percentage into margin value. However I am not sure how to do this without breaking the MVVM pattern and accessing the "canvas" from the ViewModel to get it's size.
For example, if the canvas is 100 wide and the X position is 0.1 then I need the left margin to be 10.
I thought about using a command and sending the canvas width/height as an event argument but I am not sure where I would bind this.
XAML
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Position" Width="75"/>
<TextBox Height="25" Width="50"
Text="{Binding Path=X, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Height="25" Width="50"
Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
<Grid Height="300" Width="550">
<TextBlock FontSize="18" FontFamily="Arial"
Opacity="{Binding Path=Opacity}"
Margin="{Binding Position}">
</TextBlock>
</Grid>
ViewModel
public double X
{
get { return Model.Position.X; }
set
{
if (Model.Position.X != value)
{
Model.Position = new Point(value, Model.Position.Y);
OnPropertyChanged("Position");
}
}
}
public double Y
{
get { return Model.Position.Y; }
set
{
if(Model.Position.Y != value)
{
Model.Position = new Point(Model.Position.X, value);
OnPropertyChanged("Position");
}
}
}
public Thickness Position
{
get { return new Thickness(Model.Position.X, Model.Position.Y, 0, 0); }
}
Upvotes: 4
Views: 3072
Reputation: 587
Solution was to use a MultiBinding
sending the needed information as the values:
<Setter Property="Margin">
<Setter.Value>
<MultiBinding Converter="{StaticResource MyMultiConverter}">
<Binding Path="X"/>
<Binding Path="Y"/>
<Binding ElementName="Canvas" Path="ActualWidth"/>
<Binding ElementName="Canvas" Path="ActualHeight"/>
</MultiBinding>
</Setter.Value>
</Setter>
MyMultiConverter then implements IMultiValueConverter
and returns a Thickness
Upvotes: 4
Reputation: 436
If I understand correctly your question, I think you just need to use a converter. You can find more info how to implement it here: http://wpftutorial.net/ValueConverters.html
Upvotes: 0