我有一個IValueConverter
名爲CategoryToGridViewConverter
它有一個名爲ListViewWidthProperty
DependencyProperty。我還從DependencyObject
繼承了我的轉換器,以便它可以與DependencyProperties一起使用。這裏是我的轉換器是如何定義的:綁定自定義依賴屬性ListView寬度不更新
internal class CategoryToGridViewConverter : DependencyObject, IValueConverter
{
public static readonly DependencyProperty ListViewWidthProperty = DependencyProperty.Register("ListViewWidth", typeof (double),
typeof (CategoryToGridViewConverter), new PropertyMetadata(0d, PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
Debug.WriteLine("ListViewWidth: " + dependencyPropertyChangedEventArgs.NewValue);
}
public double ListViewWidth {
get { return (double)GetValue(ListViewWidthProperty); }
set { SetValue(ListViewWidthProperty, value); }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//Not relevant
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//Not relevant
}
}
}
很簡單。然後,我創建XAML中該轉換器(在ListView的參考資料)是這樣的:
<ListView Grid.Row="0" BorderThickness="0"
ItemsSource="{Binding SelectedCategory.Entries}"
x:Name="listView"
SizeChanged="ListView_OnSizeChanged">
<ListView.Resources>
<local:CategoryToGridViewConverter x:Key="CategoryToGridViewConverter" ListViewWidth="{Binding listView, Path=Width, Mode=OneWay}"/>
</ListView.Resources>
<ListView.View>
<Binding Path="SelectedCategory" Converter="{StaticResource CategoryToGridViewConverter}"/>
</ListView.View>
</ListView>
但問題是,ListViewWidth
從未更新。它始終保持在0.但是ListView有問題顯然不是0寬度。
我在做什麼錯?
編輯:這也給輸出屏幕上綁定錯誤:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Width; DataItem=null; target element is 'CategoryToGridViewConverter' (HashCode=33594544); target property is 'ListViewWidth' (type 'Double')
是否DependencyProperties只爲FrameworkElements工作?如果是這樣,我的轉換器怎麼會知道ListView的寬度?
一個'DependencyProperty'只能在一個'DependencyObject'據我所知聲明。例如,該類爲您提供了'SetValue'和'GetValue'。如果你只有'CategoryToGridViewConverter'的'IValueConverter'接口,我真的不知道如何編譯。您能否在轉換器的完整實施中更新您的答案? –
我已更新我的問題 –
謝謝,您能否插入轉換器的用法?我可以看到你把它放到'Resources'集合或'ResourceDictionary'中,但你想在哪裏使用它? –