Frage

Let me rephrase my question, cause I feel like I'm getting unrelated answers.

Assume I have a ViewModel in which I want to have a property that has a percentage that defines say... uh, a completion bar. And I have a View that has nothing more than a rectangle.

How would I go about and creating a binding that allows me to set the rectangle's width to a certain percentage of it's displayed width in the View, -without- making use of ScaleTransform?

==========================

In my WPF program I have a View which uses several of these:

//part of PlayerView.xaml

<Border Background="#777700" Canvas.Left="5" Canvas.Top="36" Width="64" Height="16" >
    <ContentControl x:Name="HPBar" Width="50"/>
</Border>

//part of PlayerViewModel.cs

    private Player _model;
    public PlayerViewModel(Player player)
    {
        _model = player;
        ///===CAN I GET THE WIDTH OF THE CONTENTCONTROL HERE?===///
        HpBar = new StatBarViewModel(int WIDTH, int maxValue);
    }

    private StatBarViewModel _hpBar;
    public StatBarViewModel HPBar { get { return _hpBar; } set { _hpBar = value; NotifyOfPropertyChange("HPBar"); } }

Using Caliburn Micro, these are properly linked to a few StatBar controls. What I want is the above widths to be available as a variable below. This so I can set the bar Width to be, say, half it's original size. I do want to set the values absolute, so scaling is not an option for me.

public class StatBarViewModel : AnimatedViewModelBase
{
    private int MAXIMUMWIDTHFROMVIEW;

    public StatBarViewModel(int WIDTH, int maxValue)
    {
       _max = maxValue;
       MAXIMUMWIDTHFROMVIEW = WIDTH;
    }

    private int _max;
    private int _current;
    public int Current { get { return _current; } set { (value / _max) * --MAXIMUMWIDTHFROMVIEW--; } } 
}
War es hilfreich?

Lösung

  1. Does your Current property actually compile? I'm not sure of what you are trying to achieve in the setter.

  2. To control the width from the viewmodel, you would need to

    a. create a Width property that notifies the view when the value changes

    b. bind the Width property of the control to your viewmodel variable.

ViewModel

public class StatBarViewModel : AnimatedViewModelBase
{
    private int MAXIMUMWIDTHFROMVIEW;
    private int _max;

    public StatBarViewModel(int WIDTH, int maxValue)
    {
       _max = maxValue;
       MAXIMUMWIDTHFROMVIEW = WIDTH;
    }

    private int _current;
    public int Current 
    { 
        get { return _current; } 
        set 
        { 
            // makes sure value is never greater than max value
            _current = (value > _max) ? _max : value;  
            NotifyOfPropertyChange("Current");
        } 
    } 
}

View

...

<ContentControl x:Name="HPBar" Width="{Binding Path=Current}"/>

...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top