很可能我正在以错误的方式为我的UserControl进行数据绑定,请指出一个错误。
我的页面视图(view.xaml)在XAML中显示了一个view.xaml:
<StackPanel Grid.Row="1" Margin="0,20,0,0" x:Name="ProgressBarPanel" HorizontalAlignment="Center">
<deusControls:BookProgressBar BookProgressValue="{Binding BookProgressInfo, Mode=OneWay}" Width="430" />
</StackPanel>控件本身只是一个包装的列表框(myprogressbar.xaml):
<Grid x:Name="ProgressBarLayoutRoot">
<ListBox x:Name="ProgressBarControl" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Bars, RelativeSource=this}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border Height="15" BorderThickness="1" CornerRadius="{Binding Corner}" Width="{Binding Width}" Background="{Binding IsAchieved, Converter={StaticResource progressToColor}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>BookProgressValue在控件后面的代码中注册为依赖项属性:
public BookProgressInfo BookProgressValue {
get { return (BookProgressInfo)GetValue(BookProgressValueProperty); }
set { SetValue(BookProgressValueProperty, value); }
}
public static readonly DependencyProperty BookProgressValueProperty =
DependencyProperty.Register("BookProgressValue", typeof(BookProgressInfo), typeof(BookProgressBar),
new PropertyMetadata(new BookProgressInfo(0), new PropertyChangedCallback(BookProgressValueChanged)));
static void BookProgressValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var bookProgressBar = (BookProgressBar)sender;
var progressInfo = (BookProgressInfo) e.NewValue;
if(progressInfo != null && progressInfo.Id != 0)
bookProgressBar.DataContext = new BookProgressBarViewModel(progressInfo, bookProgressBar.Width);
}BookProgressValue="{Binding BookProgressInfo, Mode=OneWay}"应该绑定到视图视图模型中的BookProgressInfo属性。
视图模型从逻辑中接收一个新数据,将其作为BookProgressInfo属性值提交给UI,并调用一个NotifyPropertyChanged("BookProgressInfo");。
此时,我希望我的控件处理BookProgressValueChanged事件,以更新控件自己的数据上下文(基本上是获得它绑定到的一组更新的条形图)。但BookProgressValueChanged并不是在NotifyPropertyChanged之后提出的。
的主要问题是:获取视图具有一个DataContext的正确方法是什么,而放置在视图中的UserControl是自己的,基于通过数据库设置的依赖属性的值?
如果问题的解释不清楚,请告诉我,我会改进的。谢谢。
发布于 2011-12-02 11:04:04
我认为您应该在根网格中添加这一行:
<Grid x:Name="ProgressBarLayoutRoot"
DataContext="{Binding ElementName=userControl, BookProgressValue}"并向您的UserControl添加名称:
<UserControl x:Name="userControl" 发布于 2011-12-02 02:10:45
显然,Binding for the ListBox.ItemsSource是错的: Silverlight中没有“RelativeSource=this”。
在ContentControl Template through Property中给出了正确执行此操作的几个选项。请看一看。
https://stackoverflow.com/questions/8350224
复制相似问题