使用依赖项属性 (UWP) 从用户控件检索值



>我有一个这样的自定义用户控件

<Grid>
<ListView x:Name="LView" SelectedIndex="{Binding SelectedIndex}" ItemsSource="{x:Bind 
ItemsSource, Mode=OneWay}" Width="{x:Bind Width}" Height="{x:Bind Height}"  VerticalAlignment="Stretch"   SelectionMode="Multiple"  />
</Grid>

现在在代码隐藏中,我正在尝试使用依赖项属性获取其 SelectedIndex

public int SelectedIndex
{
get { return (int)GetValue(SelectedIndexProperty); }
set { SetValue(SelectedIndexProperty, value); }
}
public static readonly DependencyProperty SelectedIndexProperty =
DependencyProperty.Register("SelectedIndex", typeof(int), typeof(CustomControl), new PropertyMetadata(0));

在我的主页中,我正在访问这样的依赖属性

<local:CustomControl Grid.Column="0" Grid.Row="0"  Width="400"    Loaded="EditTextControl_Loaded"
x:Name="MultiCombo"     ></local:CustomControl>

代码隐藏

var selIndex = MultiCombo.SelectedIndex;

但是既没有在选定的索引更改(在主页中(上触发事件,也没有在我的主页上获得任何值。我怎样才能做到这一点?注意:我在这里上传了完整的代码

在自定义控件页中,将 ListView 的 SelectedIndex 属性与 SelectedIndex 依赖项属性绑定的模式是 OneWay,当您在 ListView 中选择其他项时,SelectedIndex 依赖项属性不会更改,因此主页中 MultiCombo.SelectedIndex 的值不会更改。在这种情况下,您需要将模式设置为 TwoWay。

CustomControl.xaml:

<ListView x:Name="LView" SelectedIndex="{x:Bind SelectedIndex,Mode=TwoWay}" ItemsSource="{x:Bind ItemsSource, Mode=OneWay}" Width="{x:Bind Width}" Height="{x:Bind Height}"  VerticalAlignment="Stretch" SelectionMode="Multiple"  />

在主页中,订阅DataContextChanged事件以获取 SelectedIndex 依赖项属性,但此事件仅在当前页的 DataContext 更改时发生。如果要在 ListView 的选定索引发生更改时触发主页中的方法,可以在主页中定义一个依赖项属性,以与 CustomControl 的 SelectedIndex 依赖项属性绑定,并添加在检测到属性值更改时自动调用的静态回调方法。例如:

主页.cs:

public int MPSelectedIndex
{
get { return (int)GetValue(MPSelectedIndexProperty); }
set { SetValue(MPSelectedIndexProperty, value); }
}
public static readonly DependencyProperty MPSelectedIndexProperty =
DependencyProperty.Register("MPSelectedIndex", typeof(int), typeof(MainPage), new PropertyMetadata(0, new PropertyChangedCallback(OnDataChanged)));
private static void OnDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MainPage currentPage = d as MainPage;
int count = currentPage.MultiCombo.SelectedIndex;
}

MainPage.xaml:

<local:CustomControl Grid.Column="0" Grid.Row="0"  Width="400" Loaded="EditTextControl_Loaded" x:Name="MultiCombo"  SelectedIndex="{x:Bind MPSelectedIndex,Mode=TwoWay}" >
</local:CustomControl>

注意:由于将 ListView 的SelectionMode设置为Multiple,因此当您选择第一项时,"选定索引"为 0,然后您还选择第二项,因此"选定索引"仍为 0。仅当您取消选择第一项时,SelectedIndex 才会更改并触发该方法。

我认为问题是您没有正确绑定SelectedIndex。 与其绑定到 self/ListViewSelectedIndex,你需要绑定到自定义控件的SelectedIndexDependencyProperty

<ListView ... SelectedIndex="{Binding
Path=SelectedIndex,
Mode=TwoWay,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type UserControl}}}" .../>

您可能需要根据需要将类型更改为自定义控件的类型(如果未UserControl(。

最新更新