我动态创建了两个矩形,它们看起来像矩形,并处理了拖放事件,以便它们可以在Canvas中移动。稍后,当我按下UI上的某个按钮时,我想向画布中的每个Thumb动态添加一些字符串。有没有办法做到这一点。请帮忙。
Xaml:
<uwpControls:LayoutTransformControl x:Name="MainLayoutControl" Grid.Row="4" Height="400" Width="600" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid Grid.Row="4" x:Name="gridBarImagePanel" BorderBrush="Black"
BorderThickness="2">
<Image x:Name="BarCodeImage"
RenderTransformOrigin="0.5,0.5"></Image>
<Canvas x:Name="cnvBarCodeImage">
</Canvas>
</Grid>
</uwpControls:LayoutTransformControl>
后面的代码:
private void CreateUIShapes(int numberOfWindows, List<Dimensions> dimensions)
{
Thumb th = null;
for (int i = 0; i < numberOfWindows; i++)
{
th = new Thumb();
th.Name = i.ToString();
var item = dimensions[i];
th.Width = item.Width;
th.Height = item.Height;
th.Foreground = new SolidColorBrush(Windows.UI.Colors.Transparent);
th.BorderBrush = item.BorderColor;
th.BorderThickness = new Thickness(3);
th.DragDelta += (sender, e) => Th_DragDelta(sender, e, dimensions);
th.DragCompleted += (sender, e) => Th_DragCompleted(sender, e, item.IsImageRotated);
//RotateWindowsByAngle(90, th, dimensions, i);
Canvas.SetLeft(th, item.left);
Canvas.SetTop(th, item.Top);
cnvBarCodeImage.Children.Add(th);
}
}
private void BtnScan_Click(object sender, RoutedEventArgs e)
{
//How can I add some text to the Thumb controls at this point. There is no Children Property.
}
答案 0 :(得分:1)
由于Thumb
不是ContentControl
,因此您必须为其提供自定义ControlTemplate
才能向其中添加文本。
这是一个简单的示例,展示了如何在代码中执行此操作:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
using System.Windows.Media;
namespace WpfApp4
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var thumb = new Thumb
{
Width = 100,
Height = 50,
Background = new SolidColorBrush(Colors.Red),
Foreground = new SolidColorBrush(Colors.White),
Template = GetThumbTemplate("")
};
Canvas.SetLeft(thumb, 100);
Canvas.SetTop(thumb, 100);
RootCanvas.Children.Add(thumb);
thumb.Template = GetThumbTemplate("Hello world!");
}
private ControlTemplate GetThumbTemplate(string text)
{
var template = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"Thumb\">" +
"<Border Background=\"{TemplateBinding Background}\">" +
"<TextBlock VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" Text=\"" + text + "\" />" +
"</Border>" +
"</ControlTemplate>";
return XamlReader.Parse(template) as ControlTemplate;
}
}
}
创建Thumb
时,我将Template
设置为GetThumbTemplate
并传入一个空字符串。 GetThumbTemplate
用ControlTemplate
和Border
创建一个简单的TextBlock
。然后,我解析XAML并将其返回。
将其添加到Canvas
后,我使用Template
方法更新Thumb
的{{1}},并传入要显示的字符串。
我希望这会有所帮助!