这是我的XAML:
<Window x:Class="Gui.Wpf.MoveElementWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:Gui.Wpf.Converters"
Title="Move the red element" Height="300" Width="500">
<Window.Resources>
<!-- Converter for element location -->
<converters:LocationConverter x:Key="LocationConverter" />
</Window.Resources>
<Grid>
<Rectangle
Name="RedRectangle"
Width="150"
Height="80"
Stroke="Black"
Fill="Red"
MouseDown="RedRectangle_MouseDown"
MouseMove="RedRectangle_MouseMove" />
<TextBlock
Name="StatusTextBlock"
HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
</Grid>
</Window>
我希望能够将RedRectangle
屏幕上的StatusTextBlock
位置数据绑定到Text
的{{1}}属性,即我希望StatusTextBlock
说:“红色矩形的位置是:例如12,18“。
我为Point
到String
转换创建了一个转换器:
[ValueConversion(typeof(Point), typeof(String))]
public class LocationConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
Point location;
string valueString;
location = (Point)value;
valueString = string.Format("Red rectangle's location is: {0}, {1}",
location.X, location.Y);
return valueString;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
我不知道的是如何数据绑定矩形的位置,因为它不是通过属性提供的,而是通过一种方法来代替:RedRectangle.PointToScreen(new Point(0,0));
。请帮忙,谢谢。
答案 0 :(得分:1)
问题是您的矩形位于错误类型的面板(或容器)中。您正在使用Grid将其子项排列到由多个行/列定义的单元格中。您需要一个允许您将位置指定为像素坐标的容器。为此你需要一个画布:
<Canvas>
<Rectangle
Name="RedRectangle"
Canvas.Left="{Binding Path=Text, ElementName=StatusTextBlock, Converter={StaticResource LocationConverterLeft}}"
Canvas.Top="{Binding Path=Text, ElementName=StatusTextBlock, Converter={StaticResource LocationConverterTop}}"
Width="150"
Height="80"
Stroke="Black"
Fill="Red"
MouseDown="RedRectangle_MouseDown"
MouseMove="RedRectangle_MouseMove" />
</Canvas>
注意,您需要转换器,一个用于顶部,另一个用于左侧属性。
答案 1 :(得分:0)
您可以传入元素本身,然后调用方法:
public class LocationConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var uiElement = value as UIElement;
if (uiElement == null)
return "";
var location = uiElement.PointToScreen(0,0);
valueString = string.Format("Red rectangle's location is: {0}, {1}",
location.X, location.Y);
return valueString;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
绑定将是:
<TextBlock Text={Binding ElementName=RedRectangle}" Name="StatusTextBlock" HorizontalAlignment="Left" VerticalAlignment="Bottom" />
没试过,但这应该有用。