如何在ViewModel中获取ContentControl宽度?

时间:2014-04-03 22:26:31

标签: c# wpf caliburn.micro

让我重新解释一下我的问题,因为我觉得我得到了无关的答案。

假设我有一个ViewModel,我想在其中拥有一个属性,该属性具有定义说...呃,完成条的百分比。我有一个只有一个矩形的视图。

如何创建一个绑定,允许我将矩形的宽度设置为视图中显示宽度的某个百分比,而不使用ScaleTransform?

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

在我的WPF程序中,我有一个使用其中几个的视图:

// PlayerView.xaml的一部分

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

// 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"); } }

使用Caliburn Micro,它们与一些StatBar控件正确链接。 我想要的是上面的宽度可用作下面的变量。这样我就可以将条宽度设置为原始尺寸的一半。我确实想要设置绝对值,因此缩放对我来说不是一个选项。

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--; } } 
}

1 个答案:

答案 0 :(得分:0)

  1. 您的Current属性是否实际编译?我不确定你在设置器中想要达到的目标。

  2. 要控制viewmodel的宽度,您需要

    一个。创建一个Width属性,在值更改时通知视图

    湾将控件的Width属性绑定到viewmodel变量。

  3. 视图模型

    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");
            } 
        } 
    }
    

    查看

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