如何使用代码隐藏更改添加到C#中的画布的UserControl的宽度?

时间:2016-01-24 06:25:37

标签: c# canvas microsoft-metro code-behind

使用Visual Studion 2015,C# Metro Style应用程序 仅在Code Behind中工作。

问题:我已将userControl添加到画布。我想改变控件的宽度。

canvas提供了两个用于移动UserControls的函数:     Canvas.SetLeft,Canvas.SetTop

这两个函数正常工作,因此我知道可以访问控件属性。我试图访问我的UserControl(StickyNote)的宽度属性来调整画布上的控件的大小。 StickyNote默认设置为200x200大小,当它被添加到画布时。

当我将鼠标光标移动到画布上的UserControl上时,将调用Control_ManipulationDelta。此代码位于我的Main.xaml页面中。

<div id=container>
   <div id=div1 class=bullseye>
      <div id=div2>
         This box is centered<br>
         horizontally and vertically.
      </div>
   </div>
</div>

StickyNote是一个UserControl,在XAML页面上有一个文本字段。 当调用SetValue for WidthProperty时,它会进入StickNote代码并将Width更新为800.即使Width参数设置为800,它也不会在画布上更改。它显示了StickyNote和ManipulationDelta中的变化。这是一个持久的变化,并在下次调用ManipulationDelta时出现。 画布不会将文本字段更新为新大小。

private void Control_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    // StickyNote is my custom class that is added to the canvas
    StickyNote myControl2 = (StickyNote)sender;

    // Calculating the new location of the mouse
    xPoint = xPoint + e.Delta.Translation.X;
    yPoint = yPoint + e.Delta.Translation.Y;

    // Setting the controls left and top based on mouse position
    Canvas.SetLeft(myControl2, Canvas.GetLeft(myControl2) + xPoint);
    Canvas.SetTop(myControl2, Canvas.GetTop(myControl2) + yPoint);

    // Resetting our points
    xPoint = 0;
    yPoint = 0;

    // Setting Width - works to send values to custom control
    // But the canvas fails to update.
    myControl2.SetValue(WidthProperty,  800); // 500 to 800 as test. 
}

希望有人可以向我展示一个代码示例,它可以更改添加到画布的自定义控件的宽度,或者指向正确的方向。   谢谢,       射线

2 个答案:

答案 0 :(得分:0)

例如,您的文本字段可能具有Width的绝对300。如果是这样,您是否调整外部容器的大小并不重要。它的Width始终设置为300。如果您希望在调整包含UserControl StickyNote的{​​{1}}大小时更改宽度,请不要指定任何宽度属性(MinWidthMaxWidth,{{1} })在文本字段上,将其Width设置为HorizontalAlignment

答案 1 :(得分:0)

解决方案是修复我的XAML。我在宽度和高度上有硬编码大小。还需要查看Min Minidth和Min Height。这些需要绑定到我使用Dependency Object设置的属性。希望这有助于其他可能面临类似问题的人。