开发者

accessing a visual element in code

I would like to do the equivalent of the following xaml in code, but I don't know how to grab that text block element:

<local:DayOfTheWeekColumn 
    ...
    <local:DayOfTheWeekColumn.Header>
        <TextBlock 
            Text="{Binding ...}, 
            ToolTip="{Binding ...} />                                  
    </local:DayOfTheWeekColumn.Header>
</local:DayOfTheWeekColumn>

The DayOfTheWeekColumn is a subclass of a DataGridTextColumn. I can get at the Header easily enough and set it's content, and now I want to set the ToolTip in code, figuring the way to do that is just how I am doing it in the xaml above.

Cheers,

Berryl

EDIT =========

Here is the code, so far, for the DayOfTheWeekColumn. The TextBlock in the xaml is part of the Header's visual tree, and not something I want to keep in the xaml. I do want to access it's toolTip though, in code, so I can set it there.

I am thinking there should be a开发者_开发技巧 Children property on the column Header that I can access to find the TextBlock, but haven't found that yet.

public class DayOfTheWeekColumn : DataGridTextColumn
{
    public static readonly DependencyProperty DowDateProperty = DependencyProperty.RegisterAttached(
        "DowDate", typeof (DateTime), typeof (DayOfTheWeekColumn), new PropertyMetadata(OnDateChanged));

    public DateTime DowDate
    {
        get { return (DateTime)GetValue(DowDateProperty); }
        set { SetValue(DowDateProperty, value); }
    }

    private static void OnDateChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) {
        var col = (DataGridTextColumn) target;
        var date = (DateTime) e.NewValue;

        col.Header = date.ToString(Strings.ShortDayOfWeekFormat);
        //col.Header.ToolTip = "If Only It Were so Easy!!" <==============
    }

    public DayOfTheWeekColumn() {
        Width = 60;
        CanUserReorder = false;
        CanUserResize = false;
        CanUserSort = false;
    }
}


p161 of Chris Andersen's Essential Windows Presentation Foundation pretty much answers this question. If you have it, I recommend it as a reference.

However, you are so close I am not sure how you missed it :)

private static void OnDateChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) {
    var col = (DataGridTextColumn) target;
    var date = (DateTime) e.NewValue;

    var textblock = new TextBlock();
    col.Header = textblock;
    textblock.Text = date.ToString(Strings.ShortDayOfWeekFormat);
    textblock.ToolTip = "It is that easy. :)";
}


Give your TextBlock a name with the x:Name attribute and you should be able to access it in code by that name.

<TextBlock x:Name="textBlock1" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜