2009-08-17 12 views
2

我正在學習WPF中的綁定。當1)一個控件的文本直接進入另一個控件的文本域時,我可以綁定工作,2)當我在代碼隱藏文件中手動配置綁定時。純粹在XAML中定義綁定時,可以在代碼後面訪問源變量嗎?

在第一種情況下,我使用純粹的XAML來配置綁定。是否可以在代碼隱藏文件中從XAML訪問源變量?

<Window x:Class="DataBindingExperiments.MainWindow" 
    ... 
    xmlns:local="clr-namespace:DataBindingExperiments.DataSources"> 
    <Window.Resources> 
     <local:Person x:Key="MyPerson" /> 
    </Window.Resources> 
    <Grid> 
     <StackPanel Orientation="Vertical"> 
      <GroupBox Header="XAML Binding" Width="Auto" Height="110" Margin="5,5,5,5"> 
       <Grid> 
        ...  
        <Grid.DataContext>  
         <Binding Source="{StaticResource MyPerson}" />  
        </Grid.DataContext>  
        <TextBox Grid.Row="0" Grid.Column="1" Name="textBox_firstName" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />  
        <TextBox Grid.Row="1" Grid.Column="1" Name="textBox_lastName" Text="{Binding Path=LastName, UpdateSourceTrigger=PropertyChanged}"/>  
        <TextBlock Grid.Row="2" Grid.Column="1" Name="textBox_fullName" Text="{Binding Source={StaticResource MyPerson}, Path=FullName}" />  
       </Grid> 
... 
... 

在上面的代碼,我怎麼訪問代碼隱藏「MyPerson」的實例?

回答

4

那麼,在這種情況下,它很容易,因爲它定義爲一個資源:

object MyPerson = FindResource("MyPerson"); 

在一般情況下,這是一個比較複雜......假設你有一個TextBox名爲textBox1,其Text屬性被綁定到另一個對象的Name屬性,你可以做這樣的事情:

BindingExpression expr = BindingOperations.GetBindingExpression(textBox1, TextBox.TextProperty); 
object source = expr.DataItem; 
+0

@Thomas:很巧,我不知道DataItem屬性:) – Pwninstein 2009-08-17 18:57:24

+1

也沒有我;)我迷迷糊糊同時在文檔中查找BindingExpression ... – 2009-08-17 19:23:33

+0

@ThomasLevesque在Silverlight的情況下我們可以做什麼?我找不到GetBindingExpression for Silverlight – 2015-08-18 11:42:43

4

我相信你必須在窗口的Window_Loaded事件中做Person p = (Person)FindResource("MyPerson");。我不認爲您可以爲ResourceDictionary中的項目指定名稱。

相關問題