2010-04-21 96 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属性(并因此在运行时更改它)。