2012-12-16 49 views
4

背後屬性的代碼,這是我第一次的帖子,所以moght不看那麼好,但我會盡我所能...訪問在XAML

我一直在尋找的淨這一個現在幾個小時,這聽起來可能很愚蠢,但我一直無法找到答案。

我有窗口類,並在.cs文件我有一些特性,例如

public ImageSource Obal { get; set; } 

然後在設計師,我加了一些圖片,按鈕等也設置窗口的名稱:名稱=「Somename」

我想知道如何訪問該屬性,這樣我就可以,例如,一些圖像的源屬性設置爲,就像這樣:

圖片名稱=「嗒嗒」源=「OB人」

現在我知道我可以通過綁定設置源值:

來源=‘{綁定的ElementName =顯示地圖,路徑= 10:28}’

但我不得不這樣它每次都這樣?所有這些特性都是從Window類反正...和IM還問,因爲我想在Image.Style改變image.Source故事板 ...我不能使用綁定有...

我希望我很清楚,我提前感謝大家。

回答

2

要訪問後面的代碼屬性在XAML文件,你需要遵循3個步驟:

  1. 參考命名空間中的XAML文件,如:

    xmlns:local="clr-namespace:AccessACodeBehindPropertyinXaml" 
    
  2. 提供一鍵命名空間你在Windows.Resources標記中提到過。這個鍵允許訪問任何類,XAML文件中引用的命名空間的屬性,例如

    <Window.Resources> 
         <local:ImageClass x:Key="imageClass"/> 
    </Window.Resources> 
    
  3. 現在,你只需要在XAML控件的屬性綁定,通過使用綁定類的來源& Path屬性如下:

    <Label Content="{Binding Source={StaticResource imageClass}, Path=ImageName}" Name="label1" /> 
    

我寫了一個示例應用程序結合一個類屬性到一個標籤控件。看看

MainWindow.xaml.cs文件:

namespace AccessACodeBehindPropertyinXaml 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent();      
     } 
    } 

    public class ImageClass 
    { 
     string m_ImageName; 

     public ImageClass() 
     { 
      m_ImageName = "My Image Name"; 
     } 
     public string ImageName 
     { 
      get 
      { 
       return m_ImageName; 
      } 
      set 
      { 
       m_ImageName = value; 
      } 
     } 
    } 
} 

MainWindow.xaml

<Window x:Class="AccessACodeBehindPropertyinXaml.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:AccessACodeBehindPropertyinXaml" 
     Title="MainWindow" Height="350" Width="525" Name="ImageWindow"> 
    <Window.Resources> 
     <local:ImageClass x:Key="imageClass"/> 
    </Window.Resources> 
    <Grid> 
     <Label Content="{Binding Source={StaticResource imageClass}, Path=ImageName}" Height="28" HorizontalAlignment="Left" Margin="159,126,0,0" Name="label1" VerticalAlignment="Top" Width="109" /> 
    </Grid> 
</Window> 

請讓我知道,如果你需要任何更多的澄清。

+0

請不要縮進文本,除非您希望它被格式化爲代碼。 –

+1

謝謝你的回答,但我希望有更多的sthraightforward訪問該屬性的方式,而不是通過綁定...因爲有了這個屬性,我試圖設置一個圖像的源內故事板,它的風格,並且它不能用綁定來完成(我得到「無法凍結這個Storyboard時間軸樹以供跨線程使用」),只有StaticResource ...對我來說沒用,因爲該屬性是在Window的構造函數中設置的。 –