首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XAML:更改DataContext时的更新绑定

问XAML:更改DataContext时的更新绑定
EN

Stack Overflow用户
提问于 2011-07-04 11:23:24
回答 5查看 9.6K关注 0票数 3

我有一个简单的XAML文件,它包含一个标签,其前台属性包含绑定:

代码语言:javascript
复制
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="200" Height="100" >
    <Label Content="Sampletext" Foreground="{Binding Path=Color}" />
</Grid>

当我加载模板并应用DataContext时,前台仍然具有默认值。在不使用渲染网格的情况下,可以获得绑定的前景值吗?

代码语言:javascript
复制
// Load template
string templatePath = "/WpfApplication1;component/Template.xaml";
Grid grid = Application.LoadComponent(new Uri(templatePath, UriKind.Relative)) as Grid;

// Set dataContext
grid.DataContext = new { Color = Brushes.Green };

// Foregound still has default value
var foreground = ((Label)grid.Children[0]).Foreground;

项目可在以下位置下载:http://dl.dropbox.com/u/21096596/WpfApplication1.zip

EN

回答 5

Stack Overflow用户

发布于 2011-07-04 11:31:19

试一试

代码语言:javascript
复制
lblName.GetBindingExpression(Label.ForegroundProperty).UpdateTarget();

在此之前

代码语言:javascript
复制
var foreground = ((Label)grid.Children[0]).Foreground;
票数 2
EN

Stack Overflow用户

发布于 2011-07-04 13:06:59

有自动的DataContext更改通知,如果满足必要的条件,绑定将更新。其中之一是加载了控件(IsLoaded == true),这在代码中不是这样的。只有在将控件添加到UI的某个位置时,该控件才会加载。

示例测试代码:

代码语言:javascript
复制
private void Button_Click(object sender, RoutedEventArgs e)
{
    Grid grid = null;
    Action action = () =>
        {
            var foreground = ((Label)grid.Children[0]).Foreground;
            MessageBox.Show(foreground.ToString());

            grid.DataContext = new { Color = Brushes.Green };

            foreground = ((Label)grid.Children[0]).Foreground;
            MessageBox.Show(foreground.ToString());
        };
    grid = Application.LoadComponent(new Uri("Stuff/GridOne.xaml", UriKind.Relative)) as Grid;
    if (grid.IsLoaded)
    {
        action();
    }
    else
    {
        grid.Loaded += (s, _) => action();
    }
    // This adds the grid to some StackPanel, if you do not do something like this
    // nothing will happen since the control will not be loaded and thus the event
    // will not fire, etc. 
    ControlStack.Children.Add(grid);
}
票数 1
EN

Stack Overflow用户

发布于 2011-07-04 11:27:00

为什么你需要一次绑定?把它移开,它就能工作了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6570791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档