2013-04-10 62 views
0

我有一個簡單的頁面,有一個矩形,一個橢圓,兩個滑塊和一個文本塊。如何通過函數調用設置XAML屬性?

兩個滑塊控件(通過綁定)矩形的高度和寬度。

我想根據矩形尺寸的最小值設置橢圓的寬度和高度。該XAML代碼如下所示:

<UserControl 
x:Class="App16.MyUserControl1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:App16" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" 
d:DesignHeight="400" 
d:DesignWidth="400" 
x:Name="MyRoot"> 

<Grid Background="Black"> 

    <Grid.ColumnDefinitions> 
     <ColumnDefinition /> 
     <ColumnDefinition /> 
    </Grid.ColumnDefinitions> 

    <Grid.RowDefinitions> 
     <RowDefinition Height="2*" /> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 

    <Rectangle Name="rect" Fill="Yellow" 
       Width="{Binding ElementName=rectX,Path=Value}" 
       Height="{Binding ElementName=rectY,Path=Value}" Grid.Column="0"/> 

    <Ellipse Fill="Yellow" 
      Width="{Binding ElementName=MyRoot,Path=SampleFunction}" 
      Height="{Binding ElementName=MyRoot,Path=SampleFunction}" Grid.Column="1" /> 

    <StackPanel Grid.Row="1" Grid.ColumnSpan="2">      
     <Slider Name="rectX" HorizontalAlignment="Stretch" Minimum="100" Maximum="200" Value="150" /> 
     <Slider Name="rectY" HorizontalAlignment="Stretch" Minimum="100" Maximum="200" Value="150" /> 
     <TextBlock Foreground="White" Text="{Binding ElementName=MyRoot, Path=SampleFunction}" /> 
    </StackPanel> 

</Grid> 

後面的代碼看起來是這樣的:

public Double SampleFunction {    
     get { return (rect.Width <= rect.Height ? rect.Width : rect.Height); } 
    } 

在當前狀態下,矩形調整大小適當根據滑塊的價值,但在加載頁面後,「SampleFunction」永遠不會被調用。

當然,我可以用「RESIZED」事件做到這一點,但我想知道如果沒有這樣做,這是可能的。

有什麼建議嗎?當用戶調整滑塊控件時,我希望看到矩形和橢圓更改大小。

謝謝!

回答

1

您的SampleFunction需要重命名(它是一個屬性,而不是函數)。

,並使其數據綁定需要實現INotifyPropertyChanged

另外的工作,內部邏輯也許應該是在ActualWidthActualHeight基地。

+0

由於綁定的來源是一個控件(用戶控件) - 它實際上需要成爲一個依賴屬性。 INotifyPropertyChanged不屬於controls.Then再次,這將是太多的工作,我寧願簡單地處理一個MyRoot.SizeChanged事件進行計算,如果他們實際上是必要的。 – 2013-04-10 19:11:55

+0

你是對的,我忽略了ElementName部分。 – 2013-04-10 21:05:02

1

亨克與我的意見建議,將使它的工作,但實際上對於你的情況,你可以完全取消綁定,只需設置

<Ellipse 
    Fill="Yellow" 
    VerticalAlignment="Stretch" 
    HorizontalAlignment="Stretch" 
    Stretch="Uniform" /> 
相關問題