2010-04-21 69 views
0

我有一個具有相同風格但不同名稱的重複列的網格名稱對我來說很重要,因爲我在後面的代碼中決定創建一個模板來重複元素並從XML文件讀取名稱,但是我發現我無法使用name屬性綁定請您幫我sooooooooooooooooooooooooooon是否可以綁定元素的名稱屬性?

這裏是我的代碼的一部分:

<DataTemplate x:Key="weekItemTemplate"> 
      <Gridx:Name="{Binding XPath=Container}" Style="{DynamicResource GridStyle}"> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="0.9*"/> 
        <RowDefinition Height="0.1*"/> 
       </Grid.RowDefinitions> 
       <Rectangle x:Name="Rectangle" Grid.Row="0" Margin="0,0,0,0.063"/> 
       <TextBlock x:Name="Christian" HorizontalAlignment="Left" Width="18.52" Grid.Row="1" Margin="1,0,0,0"><Run Text="08"/></TextBlock> 
       <TextBlock x:Name="Hejri" Grid.Row="1" HorizontalAlignment="Right" Width="9.773" Margin="0,0,0,0"><Run Text="۰۱"/></TextBlock> 
       <TextBlock x:Name="Persian" Margin="1,0,0,0" HorizontalAlignment="Left" Width="10"><Run Text="۰"/></TextBlock> 
      </Grid> 
     </DataTemplate> 
    </Window.Resources> 
    <Grid Margin="0,10,0,0"> 
     <Grid.DataContext> 
      <XmlDataProvider x:Name="TeamData" Source="weekdays.xml" XPath="days/day" /> 
     </Grid.DataContext> 
     <ListView x:Name="TeamsListBox" DockPanel.Dock="Left" 
        ItemsSource="{Binding}" 
        ItemTemplate="{StaticResource weekItemTemplate}" 
        IsSynchronizedWithCurrentItem="True" 
        Visibility="Visible" SelectionMode="Single" /> 
+0

你想達到什麼目的?沒有進一步的細節,我只能說:不,這是不可能的(因爲你已經發現你自己)。 – gehho 2010-04-21 11:51:50

回答

0

代碼隱藏需要名稱是靜態可解析的。也就是說,如果名稱真的是動態的,那麼如何在所有情況下編寫依賴於名稱的代碼?也許有一種方法可以修改設計,以便您不需要直接訪問weekItem視圖,但可以使用模擬weekItem視圖行爲方式的類。例如,如果您需要註冊事件或設置某些屬性,則可以改爲使用Command綁定到'WeekItemViewModel'類並公開屬性,以反映您希望視圖傳達的內容。

一旦你做到了這一點,你已經消除了對特定名稱的依賴,這意味着你可以動態加載你的數據並實例化這些WeekItemViewModel類,從而讓你從視圖的實際佈局細節中解脫出來。你的代碼可以更多地關注它想要如何交互,更少關注如何將代碼隱藏到特定的視覺效果。

1

想着它一次之後,你可以定義一個新的附加屬性爲您列和綁定你的名字從XML文件到這個屬性。然後在你的代碼中你可以訪問這個附加屬性而不是name屬性。這有幫助嗎?!

編輯:
我談論的attached dependency property。事情是這樣的:

public static class ColumnProps 
{ 
    public static readonly DependencyProperty MyCustomNameProperty = 
     DependencyProperty.RegisterAttached(
      "MyCustomName", 
      typeof(string), 
      typeof(ColumnProps) 
     ); 

    public static void SetMyCustomName(DependencyObject obj, string newValue) 
    { 
     obj.SetValue(MyCustomNameProperty, newValue); 
    } 

    public static string GetMyCustomName(DependencyObject obj) 
    { 
     return (string)obj.GetValue(MyCustomNameProperty); 
    } 
} 

然後,您可以設置該屬性在網格上,像這樣:

<Grid xmlns:local="..."> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition local:ColumnProps.MyCustomName="someName" Width="100"/> 
     <!-- ... --> 
    </Grid.ColumnDefinitions> 
    <!-- ... --> 
</Grid> 

其中xmlns:local應該是指集和命名空間,其中ColumnProps類型定義。

+0

你的意思是我應該定義一個依賴屬性? – Bahar 2010-04-21 12:09:07

+0

查看我上面的編輯... – gehho 2010-04-21 12:34:48

+0

好的,我剛剛看到你的問題已被編輯,現在我發現我的提議並沒有達到你想達到的目的。 – gehho 2010-04-21 12:38:14

0

由於在生成的代碼(BAML和生成的代碼隱藏)中用作字段名稱,因此無法綁定到name屬性(並因此在運行時更改它)。

相關問題