昨晚有朋友問:
引用
Hi,幫我講解一下WPF怎樣在Canvas或者Grid上根據變量改變 Shape的位置和形狀吧~
沒太理解問題在哪裡,不過看樣子是數據綁定方面不熟悉?
那 就寫個用到Canvas和數據綁定的例子吧。在VS2008裡新建一個WPF應用,然後把下面的Window1.xaml和 Window1.xaml.cs替換進去就行。
做出來的是像這樣的一個界面(是很丑啦 T T)
把Window裡 的根容器Grid分成上下兩行:上半部分放置用於控制和顯示坐標的控件;下半部分放置一個Canvas,裡 面放一個Rectangle。在TextBox裡輸入數字或者滑動ScrollBar都能夠改變Rectangle的位置。
也 就是隨便在VS2008的WPF Designer裡拖拖控件把界面拉出來:
Window1.xaml
Xml代碼
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="TestWpfCanvasShapeDataBinding.Window1" xmlns:Custom="http://schemas.microsoft.com/winfx/2006/xaml/composite-font" Title="Test Data Binding" Height="480" Width="230" > <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <TextBox Name="txtX" Margin="12,10,0,0" Height="23" Width="95" VerticalAlignment="Top" HorizontalAlignment="Left" Text="{Binding Path=RectX, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <Label Name="lblX" Margin="12,40,0,0" Height="23" Width="95" VerticalAlignment="Top" HorizontalAlignment="Left" Content="{Binding Path=RectX}" /> <Button Name="btnX" Margin="0,10,5,0" Height="23" Width="81" VerticalAlignment="Top" HorizontalAlignment="Right" Click="button1_Click" > Check X Value </Button> <ScrollBar Name="scbX" Margin="12,70,5,0" Height="20" Width="181" VerticalAlignment="Top" Orientation="Horizontal" Maximum="200" Value="{Binding Path=RectX, Mode=TwoWay} " /> <TextBox Name="txtY" Margin="12,120,0,0" Height="23" Width="95" VerticalAlignment="Top" HorizontalAlignment="Left" Text="{Binding Path=RectY, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <Label Name="lblY" Margin="12,150,0,0" Height="23" Width="95" VerticalAlignment="Top" HorizontalAlignment="Left" Content="{Binding Path=RectY}" /> <Button Name="btnY" Margin="0,120,5,0" Height="23" Width="81" VerticalAlignment="Top" HorizontalAlignment="Right" Click="button2_Click" > Check Y Value </Button> <ScrollBar Name="scbY" Margin="12,180,5,0" Height="20" Width="181" VerticalAlignment="Top" Orientation="Horizontal" Value="{Binding Path=RectY, Mode=TwoWay}" Maximum="200" /> <Canvas Margin="0,0,0,0" Grid.Row="1" > <Canvas.Background> <Custom:LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" > <Custom:GradientStop Color="#FF337496" Offset="0" /> <Custom:GradientStop Color="#FF94E2EC" Offset="1" /> </Custom:LinearGradientBrush> </Canvas.Background> <Rectangle Height="20" Width="20" Stroke="#FF301A87" Fill="#FF8169E6" Canvas.Left="{Binding Path=RectX}" Canvas.Top="{Binding Path=RectY}" /> </Canvas> </Grid> </Window>