2017-05-29 27 views
-1

@Update適當UpdateSourceTrigger - 見下面更新,請的DependencyProperty無法創建內部綁定時綁定未設置UpdateSourceTrigger明確

我有一個是內部DataGridTemplateColumn使用UserControl。當我指定像這樣的綁定{Binding MyProperty, UpdateSourceTrigger=PropertyChanged}它更新源。但是,我忽略了UpdateSourceTrigger它不更新源。

DependencyProperty創建這樣的:

public static readonly DependencyProperty RatingValueProperty = DependencyProperty.Register(
    "RatingValue", typeof(int?), typeof(RatingControl), new FrameworkPropertyMetadata(default(int), 
     FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
     DependencyPropertyChangedCallback, 
     CoerceRatingValueCallback, 
     false, 
     UpdateSourceTrigger.PropertyChanged 
)); 

正如你可以看到下面的BindingDefault標誌創建省略UpdateSourceTrigger時,與PropertyChanged標誌,如果沒有。

的 「不工作」 結合(見行26對兩個例子):

0 _binding {System.Windows.Data.Binding} System.Windows.Data.BindingBase {System.Windows.Data.Binding} 
1 AsyncState null object 
2 BindingGroupName "" string 
3 BindsDirectlyToSource false bool 
4 Converter null System.Windows.Data.IValueConverter 
5 ConverterCulture null System.Globalization.CultureInfo 
6 ConverterCultureInternal null System.Globalization.CultureInfo 
7 ConverterParameter null object 
8 Delay 0 int 
9 ElementName null string 
10 FallbackValue {{DependencyProperty.UnsetValue}} object {MS.Internal.NamedObject} 
11 Flags Default System.Windows.Data.BindingBase.BindingFlags 
12 IsAsync false bool 
13 Mode Default System.Windows.Data.BindingMode 
14 NotifyOnSourceUpdated false bool 
15 NotifyOnTargetUpdated false bool 
16 NotifyOnValidationError false bool 
17 Path {System.Windows.PropertyPath} System.Windows.PropertyPath 
18 RelativeSource null System.Windows.Data.RelativeSource 
19 Source null object 
20 SourceReference null MS.Internal.Data.ObjectRef 
21 StringFormat null string 
22 TargetNullValue {{DependencyProperty.UnsetValue}} object {MS.Internal.NamedObject} 
23 TransfersDefaultValue true bool 
24 TreeContextIsRequired false bool 
25 UpdateSourceExceptionFilter null System.Windows.Data.UpdateSourceExceptionFilterCallback 
26 UpdateSourceTrigger Default System.Windows.Data.UpdateSourceTrigger 
27 ValidatesOnDataErrors false bool 
28 ValidatesOnExceptions false bool 
29 ValidatesOnNotifyDataErrors true bool 
30 ValidatesOnNotifyDataErrorsInternal true bool 
31 ValidationRules Count = 0 System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule> {MS.Internal.Controls.ValidationRuleCollection} 
32 ValidationRulesInternal Count = 0 System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule> {MS.Internal.Controls.ValidationRuleCollection} 
33 XPath null string 
34 _attachedPropertiesInPath 0 int 
35 _bindsDirectlyToSource false bool 
36 _doesNotTransferDefaultValue false bool 
37 _flags Default System.Windows.Data.BindingBase.BindingFlags 
38 _isAsync false bool 
39 _isSealed true bool 
40 _ppath {System.Windows.PropertyPath} System.Windows.PropertyPath 
41 _source {MS.Internal.Data.ExplicitObjectRef} MS.Internal.Data.ObjectRef {MS.Internal.Data.ExplicitObjectRef} 
42 _sourceInUse None System.Windows.Data.Binding.SourceProperties 
43 _values {MS.Internal.UncommonValueTable} MS.Internal.UncommonValueTable 
44 Static members  

「工作」 結合:

0 _binding {System.Windows.Data.Binding} System.Windows.Data.BindingBase {System.Windows.Data.Binding} 
1 AsyncState null object 
2 BindingGroupName "" string 
3 BindsDirectlyToSource false bool 
4 Converter null System.Windows.Data.IValueConverter 
5 ConverterCulture null System.Globalization.CultureInfo 
6 ConverterCultureInternal null System.Globalization.CultureInfo 
7 ConverterParameter null object 
8 Delay 0 int 
9 ElementName null string 
10 FallbackValue {{DependencyProperty.UnsetValue}} object {MS.Internal.NamedObject} 
11 Flags PropDefault | ValidatesOnNotifyDataErrors System.Windows.Data.BindingBase.BindingFlags 
12 IsAsync false bool 
13 Mode Default System.Windows.Data.BindingMode 
14 NotifyOnSourceUpdated false bool 
15 NotifyOnTargetUpdated false bool 
16 NotifyOnValidationError false bool 
17 Path {System.Windows.PropertyPath} System.Windows.PropertyPath 
18 RelativeSource null System.Windows.Data.RelativeSource 
19 Source null object 
20 SourceReference null MS.Internal.Data.ObjectRef 
21 StringFormat null string 
22 TargetNullValue {{DependencyProperty.UnsetValue}} object {MS.Internal.NamedObject} 
23 TransfersDefaultValue true bool 
24 TreeContextIsRequired false bool 
25 UpdateSourceExceptionFilter null System.Windows.Data.UpdateSourceExceptionFilterCallback 
26 UpdateSourceTrigger PropertyChanged System.Windows.Data.UpdateSourceTrigger 
27 ValidatesOnDataErrors false bool 
28 ValidatesOnExceptions false bool 
29 ValidatesOnNotifyDataErrors true bool 
30 ValidatesOnNotifyDataErrorsInternal true bool 
31 ValidationRules Count = 0 System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule> {MS.Internal.Controls.ValidationRuleCollection} 
32 ValidationRulesInternal Count = 0 System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule> {MS.Internal.Controls.ValidationRuleCollection} 
33 XPath null string 
34 _attachedPropertiesInPath 0 int 
35 _bindsDirectlyToSource false bool 
36 _doesNotTransferDefaultValue false bool 
37 _flags PropDefault | ValidatesOnNotifyDataErrors System.Windows.Data.BindingBase.BindingFlags 
38 _isAsync false bool 
39 _isSealed true bool 
40 _ppath {System.Windows.PropertyPath} System.Windows.PropertyPath 
41 _source {MS.Internal.Data.ExplicitObjectRef} MS.Internal.Data.ObjectRef {MS.Internal.Data.ExplicitObjectRef} 
42 _sourceInUse None System.Windows.Data.Binding.SourceProperties 
43 _values {MS.Internal.UncommonValueTable} MS.Internal.UncommonValueTable 
44 Static members  

如何解決這個,所以我不必在WPF中顯式設置「UpdateSourceTrigger = PropertyChanged」。

@Update 2017年6月3日

我附上鍊接(click)的示例項目說明問題。請打開MainWindow.xaml並撥動#35-#39行。 #36行顯示不工作行爲,#39行顯示工作行爲。

線#36

<local:RatingControl StarsCount="5" RatingValue="{Binding Rating, PresentationTraceSources.TraceLevel=High}" IsReadonly="False" HorizontalContentAlignment="Center" /> 

線#39

<local:RatingControl StarsCount="5" RatingValue="{Binding Rating, UpdateSourceTrigger=PropertyChanged, PresentationTraceSources.TraceLevel=High}" IsReadonly="False" HorizontalContentAlignment="Center" /> 

@Edit - 請求XAML代碼

<UserControl x:Class="so_44248130.RatingControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="24" d:DesignWidth="240"> 
    <UserControl.Resources> 
     <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> 
     <BitmapImage x:Key="StarEmpty" UriSource="pack://application:,,,/so_44248130;component/star_black_empty.png" CacheOption="OnLoad" CreateOptions="IgnoreImageCache" /> 
     <BitmapImage x:Key="StarFull" UriSource="pack://application:,,,/so_44248130;component/star_black_full.png" /> 
    </UserControl.Resources> 
    <Grid> 
     <ItemsControl ItemsSource="{Binding StarsList, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <StackPanel Orientation="Horizontal" /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <Grid> 
         <Button Grid.Row="0" Grid.Column="0" Width="24" Height="24" MaxHeight="24" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Tag="{Binding}" Padding="0" HorizontalContentAlignment="Center" Click="ButtonBase_OnClick"> 
          <Grid> 
           <Grid.RowDefinitions> 
            <RowDefinition /> 
           </Grid.RowDefinitions> 
           <Grid.ColumnDefinitions> 
            <ColumnDefinition Width="24" /> 
           </Grid.ColumnDefinitions> 

           <Rectangle Grid.Row="0" Grid.Column="0" Width="{Binding EmptyStarWidth}" Height="24" HorizontalAlignment="Left"> 
            <Rectangle.Fill> 
             <ImageBrush ImageSource="{StaticResource StarEmpty}" 
             TileMode="Tile" 
             Stretch="Uniform" 
             AlignmentY="Top" 
             Viewport="0,0,24,3000" 
             ViewportUnits="Absolute" /> 
            </Rectangle.Fill> 
           </Rectangle> 
           <Rectangle Grid.Row="0" Grid.Column="0" Width="{Binding FullStarWidth}" Height="24" HorizontalAlignment="Left"> 
            <Rectangle.Fill> 
             <ImageBrush ImageSource="{StaticResource StarFull}" 
             TileMode="Tile" 
             Stretch="Uniform" 
             AlignmentY="Top" 
             Viewport="0,0,24,3000" 
             ViewportUnits="Absolute" /> 
            </Rectangle.Fill> 
           </Rectangle> 
          </Grid> 
         </Button> 
         <Rectangle Grid.Row="0" Grid.Column="0" Height="24" Width="24" Visibility="{Binding IsReadonly, Converter={StaticResource BooleanToVisibilityConverter}}" Fill="#02FFFFFF" /> 
        </Grid> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </Grid> 
</UserControl> 
+1

無論如何,FrameworkPropertyMetadata類的'DefaultUpdateSourceTrigger'屬性的值是'PropertyChanged',因此您可以使用FrameworkPropertyMetadata構造函數來創建更少的參數。也就是說,我所創建的所有具有「BindsTwoWayByDefault」的依賴項屬性都會在'PropertyChanged'上更新它們的源代碼,而不會出現任何問題,所以目前還不清楚爲什麼您的代碼不符合它。 – Clemens

+0

@Clemens我編輯了我的問題(已添加鏈接到示例項目),請親自看看 – user2475983

+0

我們可以看到RatingControl的XAML嗎? –

回答

0

我已經想通了... ...一部分

在問題鏈接的示例項目應該定位到RatingControl.xaml.cs文件,線#206-#228(click)。這是ButtonBase_OnClick方法。正好在if (star.Value ==〜部分我添加了綁定的強制UpdateSource。見下面的代碼。

if (star.Value == RatingValue) 
{ 
    RatingValue = 0; 
} 
else 
{ 
    RatingValue = star.Value; 
} 

BindingExpression binding = GetBindingExpression(RatingValueProperty); 
if (binding != null) 
{ 
    binding.UpdateSource(); 
} 

這迫使的BindingSource更新並解決此問題(這是某種形式的補救措施可能..但也許它會把人在正確的方向後真正有效的答案)。

注:

在調試我檢查接收BindingExpression並命名爲IsUpdateOnPropertyChanged的屬性設置爲false出於某種原因。我相信它應該設置爲true但是我缺乏關於WPF內部知識的知識以將其作爲答案發布,因此是「註釋」區域。

-1

是否有使用FrameworkPropertyMetadata任何具體的原因是什麼?

如果你只是備份一個屬性,然後嘗試使用PropertyMetadata

詳情請參閱here

+0

沒有具體原因。我已經將'FrameworkPropertyMetadata'更改爲'PropertyMetadata',但唯一的結果是我必須明確指定'Mode = TwoWay'在XAML的'Binding'中,所以..沒有真正幫助:(。 – user2475983

+0

我得到了問題因爲它無法找到源,請嘗試使用' – Anurag

+0

是的,它似乎有所幫助,但它看起來像另一種解決方法,你能否詳細說明爲什麼即使'DataContext'被UC繼承了也無法找到源代碼? – user2475983

相關問題