简体   繁体   中英

How to use targetname with usercontrol and trigger

I made UserControl of DataGrid. I placed this new component into page1.xaml. I would like to use some template and setting based on value in Data1.

Could you help me with this code how to avoid the error message?

<my:MyDataGrid Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" Margin="29,295,0,0" Name="myDataGrid1" 
           VerticalAlignment="Top"  Height="151" Width="176" SelectionChanged="myDataGrid1_SelectionChanged">
        <my:MyDataGrid.Columns>
            <DataGridTemplateColumn Header="Col1" >
                <DataGridTemplateColumn.CellTemplate>                        
                    <DataTemplate>
                        <TextBlock Text="{Binding Data1}" x:Name="mytext" />
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding Data1}" Value="1">
                                <Setter TargetName="mytext"  Property="Foreground" Value="Red" />
                            </DataTrigger>
                        </DataTemplate.Triggers>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </my:MyDataGrid.Columns>
    </my:MyDataGrid>

I got error message:

Cannot set Name attribute value 'mytext' on element 'TextBlock'. 'TextBlock' is under the scope of element 'MyDataGrid', which already had a name registered when it was defined in another scope.

You can add you data trigger to a style attached to a TextBlock

<my:MyDataGrid Grid.Column="1" Grid.Row="1" ...>
<DataGrid.Columns>
    <DataGridTemplateColumn Header="Col1" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Data1}" x:Name="mytext">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Data1}" Value="1">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
                </Style>
            </TextBlock.Style>
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>
</my:MyDataGrid> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM