我有一个简单的XAML文件,它包含一个标签,其前台属性包含绑定:
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="200" Height="100" >
<Label Content="Sampletext" Foreground="{Binding Path=Color}" />
</Grid>当我加载模板并应用DataContext时,前台仍然具有默认值。在不使用渲染网格的情况下,可以获得绑定的前景值吗?
// 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
发布于 2011-07-04 11:31:19
试一试
lblName.GetBindingExpression(Label.ForegroundProperty).UpdateTarget();在此之前
var foreground = ((Label)grid.Children[0]).Foreground;发布于 2011-07-04 13:06:59
有自动的DataContext更改通知,如果满足必要的条件,绑定将更新。其中之一是加载了控件(IsLoaded == true),这在代码中不是这样的。只有在将控件添加到UI的某个位置时,该控件才会加载。
示例测试代码:
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);
}发布于 2011-07-04 11:27:00
为什么你需要一次绑定?把它移开,它就能工作了。
https://stackoverflow.com/questions/6570791
复制相似问题