Wpf 为什么不是';我的用户控件与组合框绑定是否正确?
我正在尝试创建一个非常简单的用户控件,其中包含美国各州的列表。我试图通过“SelectedState”属性公开所选状态。然而,一旦这个绑定连接到另一个UserControl/form中,我就很难让它启动 用户控件的XAML如下所示:Wpf 为什么不是';我的用户控件与组合框绑定是否正确?,wpf,xaml,combobox,user-controls,Wpf,Xaml,Combobox,User Controls,我正在尝试创建一个非常简单的用户控件,其中包含美国各州的列表。我试图通过“SelectedState”属性公开所选状态。然而,一旦这个绑定连接到另一个UserControl/form中,我就很难让它启动 用户控件的XAML如下所示: <UserControl x:Class="Sample.Desktop.UserControls.StateDropdown" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pres
<UserControl x:Class="Sample.Desktop.UserControls.StateDropdown"
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"
xmlns:local="clr-namespace:Sample.Desktop.UserControls"
mc:Ignorable="d"
Width="170" Height="28"
d:DesignHeight="28" d:DesignWidth="170">
<ComboBox x:Name="cboState"
ItemsSource="{Binding StateList, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedValue="{Binding SelectedState, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Abbreviation}"></Label>
<Label> - </Label>
<Label Content="{Binding Name}"></Label>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我无法获取SelectedState的SelectedValue绑定属性以激发,因此我最终连接了SelectionChanged事件
private void cboState_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems?.Count > 0)
{
SelectedState = (USState)e.AddedItems[0];
}
}
在我的另一个用户控件中,我在XAML中有:
<uc:StateDropdown Margin="10,0,0,0" SelectedState="{Binding SelectedState}" ></uc:StateDropdown>
组合按预期填充。但是,当我更改选择时,SelectedState从未被激发/更新
我以前也尝试过使用SelectedItem而不是SelectedValue,结果相同
我肯定我遗漏了一些明显的东西,但我很难看出哪里出了问题
编辑:以下是修复绑定的方法
我删除了SelectionChanged事件。然后我修改了我的“hosting page”usercontrol以设置双向绑定:
<uc:StateDropdown Margin="10,0,0,0" SelectedState="{Binding SelectedState, Mode=TwoWay}" ></uc:StateDropdown>
当我添加该选项后,当我更改组合框值时,SelectedState开始更新。我看到的唯一内容是这一行:
SelectedValue="{Binding SelectedState, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"
由于SelectionChanged事件,您不需要它。这可能会导致问题
我还将使用双向绑定来绑定UserControl的SelectedState
希望这能对您有所帮助。
SelectedState=(USState)e.AddedItems[0]代码>这可能会破坏你的绑定,而在你的usercontrol使用中。这是在我无法使正常绑定正常工作后才添加的。我真的不希望SelectionChanged事件,因为它使双向绑定变得更加困难。它只是在正常绑定不起作用时作为测试添加的。你的建议是将SelectedState设置为双向绑定。我一这么做,ViewModel中的绑定就开始被触发。谢谢
<uc:StateDropdown Margin="10,0,0,0" SelectedState="{Binding SelectedState, Mode=TwoWay}" ></uc:StateDropdown>
SelectedValue="{Binding SelectedState, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"