Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何让单选按钮像MVVM模式中的组合框一样工作?_Wpf_Xaml_Radio Button - Fatal编程技术网

Wpf 如何让单选按钮像MVVM模式中的组合框一样工作?

Wpf 如何让单选按钮像MVVM模式中的组合框一样工作?,wpf,xaml,radio-button,Wpf,Xaml,Radio Button,在下面的代码中,用户从组合框中选择一个客户,该客户的信息显示在框中 现在我还想让单选按钮使用相同的功能。我有单选按钮来显示可观察到的客户集合,但是我如何才能让被选中工作,即单选按钮的SelectedItem的等价物是什么 XAML: <Window.Resources> <DataTemplate x:Key="CustomerShowTemplate"> <Border CornerRadius="5"

在下面的代码中,用户从组合框中选择一个客户,该客户的信息显示在框中

现在我还想让单选按钮使用相同的功能。我有单选按钮来显示可观察到的客户集合,但是我如何才能让被选中工作,即单选按钮的
SelectedItem
的等价物是什么

XAML:

<Window.Resources>

    <DataTemplate x:Key="CustomerShowTemplate">
        <Border CornerRadius="5" 
                Background="#eee" 
                Padding="5" 
                HorizontalAlignment="Left">
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="14" FontWeight="Bold" Text="{Binding FirstName}"/>
                    <TextBlock Text=" "/>
                    <TextBlock FontSize="14" FontWeight="Bold" Text="{Binding LastName}"/>
                </StackPanel>
                <TextBlock Text="{Binding Path=HireDate, 
                    StringFormat='Hired on {0:MMM dd, yyyy}'}"/>
            </StackPanel>
        </Border>
    </DataTemplate>

    <DataTemplate x:Key="CustomerComboBoxTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"/>
            <TextBlock Text=" "/>
            <TextBlock Text="{Binding LastName}"/>
        </StackPanel>
    </DataTemplate>

    <DataTemplate x:Key="CustomerRadioButtonTemplate">
        <RadioButton GroupName="CustomerRadioButtonGroup" 
            IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}">
            <TextBlock Text="{Binding LastName}"/>
        </RadioButton>
    </DataTemplate>

</Window.Resources>

<DockPanel LastChildFill="False" Margin="10">

    <ContentControl 
        DockPanel.Dock="Top"
        Margin="0 0 0 10"
        Content="{Binding SelectedCustomer}" 
        ContentTemplate="{StaticResource CustomerShowTemplate}"/>

    <StackPanel 
        DockPanel.Dock="Top"
        Margin="0 0 0 10">

        <ComboBox 
            ItemsSource="{Binding Customers}"
            ItemTemplate="{StaticResource CustomerComboBoxTemplate}"
            Margin="20"
            HorizontalAlignment="Left"
            SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>

        <ListBox 
            ItemsSource="{Binding Customers}"
            ItemTemplate="{StaticResource CustomerRadioButtonTemplate}" 
            SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>


        <TextBlock Text="{Binding Customers.Count}"/>


        <Button Content="Add Customer" Command="{Binding AddCustomerCommand}"/>


    </StackPanel>

</DockPanel>
using System;
using System.Collections.ObjectModel;
using TestSelectedItem234.Models;

namespace TestSelectedItem234.ViewModels
{
    public class MainViewModel : ViewModelBase
    {

        #region ViewModelProperty: Customers
        private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
        public ObservableCollection<Customer> Customers
        {
            get
            {
                return _customers;
            }

            set
            {
                _customers = value;
                OnPropertyChanged("Customers");
            }
        }
        #endregion

        #region ViewModelProperty: SelectedCustomer
        private Customer _selectedCustomer;
        public Customer SelectedCustomer
        {
            get
            {
                return _selectedCustomer;
            }

            set
            {
                _selectedCustomer = value;
                OnPropertyChanged("SelectedCustomer");
            }
        }
        #endregion

        #region ViewModelProperty: CustomerIsSelected
        private bool _customerIsSelected;
        public bool CustomerIsSelected
        {
            get
            {
                return _customerIsSelected;
            }

            set
            {
                _customerIsSelected = value;
                OnPropertyChanged("CustomerIsSelected");
            }
        }
        #endregion

        public MainViewModel()
        {
            LoadCustomers();

            CustomerIsSelected = false;
        }

        private void LoadCustomers()
        {
            _customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", HireDate = DateTime.Parse("2007-12-31") });
            _customers.Add(new Customer { FirstName = "Jack", LastName = "Taylor", HireDate = DateTime.Parse("2005-12-31") });
            _customers.Add(new Customer { FirstName = "Jane", LastName = "Smith", HireDate = DateTime.Parse("2005-06-30") });
            _customers.Add(new Customer { FirstName = "Alice", LastName = "Jones", HireDate = DateTime.Parse("2005-08-23") });
            _customers.Add(new Customer { FirstName = "Mary", LastName = "Ashton", HireDate = DateTime.Parse("2005-12-22") });
            _customers.Add(new Customer { FirstName = "Joe", LastName = "Jones", HireDate = DateTime.Parse("2005-11-22") });
            _customers.Add(new Customer { FirstName = "Henry", LastName = "Smith", HireDate = DateTime.Parse("2005-12-11") });
            _customers.Add(new Customer { FirstName = "Allison", LastName = "Rodrigez", HireDate = DateTime.Parse("2004-12-14") });
            _customers.Add(new Customer { FirstName = "Angela", LastName = "Thompson", HireDate = DateTime.Parse("2003-03-14") });
            _customers.Add(new Customer { FirstName = "Shawna", LastName = "Quaker", HireDate = DateTime.Parse("2005-12-14") });

            SelectedCustomer = _customers[0];
        }

    }
}


视图模型:

<Window.Resources>

    <DataTemplate x:Key="CustomerShowTemplate">
        <Border CornerRadius="5" 
                Background="#eee" 
                Padding="5" 
                HorizontalAlignment="Left">
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="14" FontWeight="Bold" Text="{Binding FirstName}"/>
                    <TextBlock Text=" "/>
                    <TextBlock FontSize="14" FontWeight="Bold" Text="{Binding LastName}"/>
                </StackPanel>
                <TextBlock Text="{Binding Path=HireDate, 
                    StringFormat='Hired on {0:MMM dd, yyyy}'}"/>
            </StackPanel>
        </Border>
    </DataTemplate>

    <DataTemplate x:Key="CustomerComboBoxTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"/>
            <TextBlock Text=" "/>
            <TextBlock Text="{Binding LastName}"/>
        </StackPanel>
    </DataTemplate>

    <DataTemplate x:Key="CustomerRadioButtonTemplate">
        <RadioButton GroupName="CustomerRadioButtonGroup" 
            IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}">
            <TextBlock Text="{Binding LastName}"/>
        </RadioButton>
    </DataTemplate>

</Window.Resources>

<DockPanel LastChildFill="False" Margin="10">

    <ContentControl 
        DockPanel.Dock="Top"
        Margin="0 0 0 10"
        Content="{Binding SelectedCustomer}" 
        ContentTemplate="{StaticResource CustomerShowTemplate}"/>

    <StackPanel 
        DockPanel.Dock="Top"
        Margin="0 0 0 10">

        <ComboBox 
            ItemsSource="{Binding Customers}"
            ItemTemplate="{StaticResource CustomerComboBoxTemplate}"
            Margin="20"
            HorizontalAlignment="Left"
            SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>

        <ListBox 
            ItemsSource="{Binding Customers}"
            ItemTemplate="{StaticResource CustomerRadioButtonTemplate}" 
            SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>


        <TextBlock Text="{Binding Customers.Count}"/>


        <Button Content="Add Customer" Command="{Binding AddCustomerCommand}"/>


    </StackPanel>

</DockPanel>
using System;
using System.Collections.ObjectModel;
using TestSelectedItem234.Models;

namespace TestSelectedItem234.ViewModels
{
    public class MainViewModel : ViewModelBase
    {

        #region ViewModelProperty: Customers
        private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
        public ObservableCollection<Customer> Customers
        {
            get
            {
                return _customers;
            }

            set
            {
                _customers = value;
                OnPropertyChanged("Customers");
            }
        }
        #endregion

        #region ViewModelProperty: SelectedCustomer
        private Customer _selectedCustomer;
        public Customer SelectedCustomer
        {
            get
            {
                return _selectedCustomer;
            }

            set
            {
                _selectedCustomer = value;
                OnPropertyChanged("SelectedCustomer");
            }
        }
        #endregion

        #region ViewModelProperty: CustomerIsSelected
        private bool _customerIsSelected;
        public bool CustomerIsSelected
        {
            get
            {
                return _customerIsSelected;
            }

            set
            {
                _customerIsSelected = value;
                OnPropertyChanged("CustomerIsSelected");
            }
        }
        #endregion

        public MainViewModel()
        {
            LoadCustomers();

            CustomerIsSelected = false;
        }

        private void LoadCustomers()
        {
            _customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", HireDate = DateTime.Parse("2007-12-31") });
            _customers.Add(new Customer { FirstName = "Jack", LastName = "Taylor", HireDate = DateTime.Parse("2005-12-31") });
            _customers.Add(new Customer { FirstName = "Jane", LastName = "Smith", HireDate = DateTime.Parse("2005-06-30") });
            _customers.Add(new Customer { FirstName = "Alice", LastName = "Jones", HireDate = DateTime.Parse("2005-08-23") });
            _customers.Add(new Customer { FirstName = "Mary", LastName = "Ashton", HireDate = DateTime.Parse("2005-12-22") });
            _customers.Add(new Customer { FirstName = "Joe", LastName = "Jones", HireDate = DateTime.Parse("2005-11-22") });
            _customers.Add(new Customer { FirstName = "Henry", LastName = "Smith", HireDate = DateTime.Parse("2005-12-11") });
            _customers.Add(new Customer { FirstName = "Allison", LastName = "Rodrigez", HireDate = DateTime.Parse("2004-12-14") });
            _customers.Add(new Customer { FirstName = "Angela", LastName = "Thompson", HireDate = DateTime.Parse("2003-03-14") });
            _customers.Add(new Customer { FirstName = "Shawna", LastName = "Quaker", HireDate = DateTime.Parse("2005-12-14") });

            SelectedCustomer = _customers[0];
        }

    }
}
使用系统;
使用System.Collections.ObjectModel;
使用TestSelectedItem234.Models;
命名空间TestSelectedItem234.ViewModels
{
公共类MainViewModel:ViewModelBase
{
#区域ViewModelProperty:客户
私有ObservableCollection_客户=新ObservableCollection();
公开收集客户
{
得到
{
退回客户;
}
设置
{
_顾客=价值;
不动产变更(“客户”);
}
}
#端区
#区域视图模型属性:SelectedCustomer
私人客户(u选择的客户);
公共客户选择客户
{
得到
{
返回所选客户;
}
设置
{
_selectedCustomer=价值;
OnPropertyChanged(“SelectedCustomer”);
}
}
#端区
#区域ViewModelProperty:客户已选择
已选择私人布尔(U)客户;
已选择公共布尔客户
{
得到
{
退货(已选择客户);;
}
设置
{
_customerIsSelected=值;
OnPropertyChanged(“客户选择”);
}
}
#端区
公共主视图模型()
{
加载客户();
CustomerIsSelected=false;
}
私人客户()
{
_添加(新客户{FirstName=“Jim”,LastName=“Smith”,HireDate=DateTime.Parse(“2007-12-31”)});
_添加(新客户{FirstName=“Jack”,LastName=“Taylor”,HireDate=DateTime.Parse(“2005-12-31”)});
_添加(新客户{FirstName=“Jane”,LastName=“Smith”,HireDate=DateTime.Parse(“2005-06-30”)});
_添加(新客户{FirstName=“Alice”,LastName=“Jones”,HireDate=DateTime.Parse(“2005-08-23”)});
_添加(新客户{FirstName=“Mary”,LastName=“Ashton”,HireDate=DateTime.Parse(“2005-12-22”)});
_添加(新客户{FirstName=“Joe”,LastName=“Jones”,HireDate=DateTime.Parse(“2005-11-22”)});
_添加(新客户{FirstName=“Henry”,LastName=“Smith”,HireDate=DateTime.Parse(“2005-12-11”)});
_添加(新客户{FirstName=“Allison”,LastName=“Rodrigez”,HireDate=DateTime.Parse(“2004-12-14”);
_新增客户{FirstName=“Angela”,LastName=“Thompson”,HireDate=DateTime.Parse(“2003-03-14”);
_添加(新客户{FirstName=“Shawna”,LastName=“Quaker”,HireDate=DateTime.Parse(“2005-12-14”)});
SelectedCustomer=_客户[0];
}
}
}
更新: 我也从Thomas那里试过,但它仍然无法连接IsChecked和IsSelected:

<ListBox ItemsSource="{Binding Customers}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <RadioButton Content="{Binding FirstName}" IsChecked="{Binding IsSelected, RelativeSource={x:Static RelativeSource.TemplatedParent}}"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Items控件没有SelectedItem属性,您应该使用列表框

此示例工作正常:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Page.Resources>
    <x:Array x:Key="stringList" Type="sys:String">
      <sys:String>Hello</sys:String>
      <sys:String>World</sys:String>
      <sys:String>!</sys:String>
    </x:Array>
  </Page.Resources>
  <Grid>
    <ListBox ItemsSource="{StaticResource stringList}">
      <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
          <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <RadioButton Content="{Binding}" IsChecked="{Binding IsSelected, RelativeSource={x:Static RelativeSource.TemplatedParent}}"/>
              </ControlTemplate>
            </Setter.Value>
          </Setter>
        </Style>
      </ListBox.ItemContainerStyle>
    </ListBox>
  </Grid>
</P

你好
世界
!

ItemsControl没有SelectedItem属性,您应该改用ListBox

此示例工作正常:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">
  <Page.Resources>
    <x:Array x:Key="stringList" Type="sys:String">
      <sys:String>Hello</sys:String>
      <sys:String>World</sys:String>
      <sys:String>!</sys:String>
    </x:Array>
  </Page.Resources>
  <Grid>
    <ListBox ItemsSource="{StaticResource stringList}">
      <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
          <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <RadioButton Content="{Binding}" IsChecked="{Binding IsSelected, RelativeSource={x:Static RelativeSource.TemplatedParent}}"/>
              </ControlTemplate>
            </Setter.Value>
          </Setter>
        </Style>
      </ListBox.ItemContainerStyle>
    </ListBox>
  </Grid>
</P

你好
世界
!

我将这一想法融入到上面的代码中并重新发布,但它似乎无法获得ISHCKED和ISSELECT之间的连接。这个解决方案非常完美,当我使用示例Customer类对其进行原型化时,它也可以工作。您能检查并确保输出窗口中没有显示任何绑定错误吗?我将这一想法合并到上面的代码中并进行了重新发布,但它似乎无法获得ISHCKED和ISSELECT之间的连接。此解决方案非常完美,当我使用示例Customer类对其进行原型化时,它也可以工作。您能检查并确保输出窗口中没有显示任何绑定错误吗?