[英]How do I change the width of a UserControl that is added to a canvas in C# using code-behind?
使用Visual Studion 2015,C#Metro Style應用程序僅在“隱藏代碼”中工作。
問題:我已將userControl添加到畫布。 我想更改控件的寬度。
畫布提供了兩種移動UserControls的功能:Canvas.SetLeft,Canvas.SetTop
這兩個功能正常工作,因此我知道可以訪問控件屬性。 我正在嘗試訪問UserControl(StickyNote)的width屬性,以在Canvas上調整控件的大小。 將StickyNote添加到畫布時,默認情況下將其設置為200x200大小。
當我將鼠標光標移到畫布上的UserControl上時,將調用Control_ManipulationDelta。 這段代碼在我的Main.xaml頁面中。
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.
}
StickyNote是一個UserControl,在XAML頁面上具有一個文本字段。 調用WidthProperty的SetValue時,它將進入StickNote代碼並將Width更新為800。即使Width參數設置為800,它在畫布上也不會更改。 它顯示了StickyNote和ManipulationDelta中的更改。 這是一個持續的更改,並在下次調用ManipulationDelta時顯示。 畫布不會將文本字段更新為新大小。
// here is the code that I used to setup my DependencyObject
public partial class StickyNote : UserControl, IPlugin, INotifyPropertyChanged
{
// Constructor
// Functions
// Update control property width
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private static void OnWidthPropertyChanged(DependencyObject
DependencyObject,
DependencyPropertyChangedEventArgs e)
{
StickyNote myUserControl = dependencyObject as StickyNote;
myUserControl.OnPropertyChanged("Width");
myUserControl.OnWidthPropertyChanged(e);
}
private void OnWidthPropertyChanged(DependencyPropertyChangedEventArgs e)
{
Width = (double)e.NewValue;
}
}
希望有人可以向我展示一個代碼示例,該示例可以更改添加到畫布上的自定義控件的寬度,也可以為我指明正確的方向。 謝謝雷
例如,您的文本字段的絕對Width
可能為300
。 如果是這樣,是否調整外部容器的大小都沒有關系。 它將始終將其Width
設置為300
。 如果要在調整包含它的UserControl
的大小時( StickyNote
)更改文本字段的寬度,請不要在文本字段上指定任何width屬性( MinWidth
, MaxWidth
, Width
)並將其HorizontalAlignment
設置為Stretch
。
解決的辦法是修復我的XAML。 我在寬度和高度上有硬編碼的尺寸。 還需要查看最小寬度和最小高度。 這些需要綁定到我使用依賴對象設置的屬性。 希望這對其他可能遇到類似問題的人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.