Most likely I am doing the databinding for my UserControl in a wrong manner, please point me to an error.
I have a UserControl decleared in XAML of my page view (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>
The control itself is simply a wrapped listbox (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>
The BookProgressValue is registered in a control’s code behind as a dependency property:
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);
}
The BookProgressValue="{Binding BookProgressInfo, Mode=OneWay}" should be binding to a BookProgressInfo property in the views view model.
The view model recieves a new data from the logic to put forward to UI as a value of BookProgressInfoproperty, and calls a NotifyPropertyChanged("BookProgressInfo");
At this point I am expecting my control to process BookProgressValueChanged event to update the control’s own data context (basically to get an updated set of Bars that it binds to.) but the BookProgressValueChanged is not raised after NotifyPropertyChanged.
Main question is:
What is the correct way of getting a view to have one DataContext, whereas a UserControl that is placed inside a view – to have it’s own, base on a value to a dependecy property set through databinging?
Please let me know if the explanation of the question is unclear, I will improve. Thank you.
I think that you should add to root grid this line:
And also add name to your UserControl: