2

I'm trying to position elements in my Canvas relative to my background.

Window is re-sized keeping the aspect ratio. Background is stretched with window size.

The problem is once window is re-sized the element positions are incorrect. If window is re-sized just a little, elements will adjust their size a bit and would be still in the correct position, but if window is re-sized to double it's size then positioning is completely off.

So far I used Grid, but it was to no avail as well. Here is the XAML

<Window x:Class="CanvasTEMP.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow"  ResizeMode="CanResizeWithGrip" SizeToContent="WidthAndHeight" MinHeight="386" MinWidth="397.5" Name="MainWindow1"
    xmlns:c="clr-namespace:CanvasTEMP" Loaded="onLoad" WindowStartupLocation="CenterScreen" Height="386" Width="397.5" WindowStyle="None" AllowsTransparency="True" Topmost="True" Opacity="0.65">

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Canvas Height="77" Width="218">
                <Label Content="{Binding OwnerData.OwnerName}" Height="36" Canvas.Left="8" Canvas.Top="55" Width="198" Padding="0" HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalAlignment="Center"/>
            </Canvas>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas>
                <Canvas.Background>
                <ImageBrush ImageSource="Resources\default_mapping.png" Stretch="Uniform"/>
                </Canvas.Background>
            </Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding OwnerData.left}" />
            <Setter Property="Canvas.Top" Value="{Binding OwnerData.top}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

Class that is used for data binding

public class Owner : INotifyPropertyChanged
{
    public double _left;
    public double _top;

    public string OwnerName { get; set; }
    public double top { get { return _top; }
        set
        {
            if (value != _top)
            {
                _top = value;
                OnPropertyChanged();
            }
        }
    }

    public double left
    {
        get { return _left; }
        set
        {
            if (value != _left)
            {
                _left = value;
                OnPropertyChanged();
            }
        }
    }

    public string icon { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = "none passed")
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class ForDisplay
{
    public Owner OwnerData { get; set; }
    public int Credit { get; set; }
}

And here is the code that is run every second to keep elements' position relative to window size

items[0].OwnerData.left = this.Width * (10 / Defaul_WindowSize_Width); 
items[0].OwnerData.top = this.Height * (55 / Defaul_WindowSize_Height);

10 and 50 are default Canvas.Left and Canvas.Top that are used when window is first initialized.

Would appreciate if anyone can point out what I'm doing wrong.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
  • What you're describing is really similar to [This Example I've created for a similar question](http://stackoverflow.com/a/16947081/643085). Check it out. – Federico Berasategui Jun 05 '13 at 20:42
  • Thanks for the feed back. I will give it a read. I'm pretty sure I solved the problem by removing Height and Width of the canvas that was holding other elements in it. – user2457280 Jun 06 '13 at 01:28

1 Answers1

0

You need an attach property:

public static readonly DependencyProperty RelativeProperty = 
    DependencyProperty.RegisterAttached("Relative", typeof(double), typeof(MyControl));

public static double GetRelative(DependencyObject o)
{
    return (double)o.GetValue(RelativeProperty);
}

public static void SetRelative(DependencyObject o, double value)
{
    o.SetValue(RelativeProperty, value);
}

and a converter:

public class RelativePositionConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var rel = (double)values[0];
        var width = (double)values[1];
        return rel * width;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

and when you add child to Canvas you need like this:

var child = new Child();
SetRelative(child, currentPosition / ActualWidth);
var multiBinding = new MultiBinding { Converter = new RelativePositionConverter() };
multiBinding.Bindings.Add(new Binding { Source = child, Path = new PropertyPath(RelativeProperty) });
multiBinding.Bindings.Add(new Binding { Source = canvas, Path = new PropertyPath(ActualWidthProperty) });
BindingOperations.SetBinding(child, LeftProperty, multiBinding);
Children.Add(child);

If you need, you can change Relative value of child separate of Canvas

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Smagin Alexey
  • 305
  • 2
  • 6