【发布时间】:2012-11-07 00:01:55
【问题描述】:
我想使用RadioButtonList 并想在初始显示时检查RadioButtonList 之一。
但ListBox 中的单选按钮无法与主题一起正常工作。
我在 ViewModel 的构造函数中将“Radio1”设置为SelectedItem1 属性。但 Radio1 在初始显示时不会被检查。如果我单击 Radio2 并单击 Radio1,则 Radio1 已正确检查。
如果我从 app.xaml 中删除主题,Radio1 在初始显示时会被正确检查。我从http://wpf.codeplex.com/releases/view/14962 下载了主题文件。
您可以通过https://github.com/koty/RadioButtonListTest下载项目。
xaml 是:
<Window x:Class="RadioButtonListTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RadioButtonListTest"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<ListBox ItemsSource="{Binding RBItems1}" SelectedItem="{Binding SelectedItem1}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<RadioButton Content="{TemplateBinding Content}"
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}" Foreground="Black"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Window>
ViewModel 是:
using System.Windows;
namespace RadioButtonListTest
{
public class MainWindowViewModel : DependencyObject
{
public MainWindowViewModel()
{
this.RBItems1 = new[] { "Radio1", "Radio2" };
this.SelectedItem1 = "Radio1";
}
public static readonly DependencyProperty RBItems1Property
= DependencyProperty.Register("RBItems1",
typeof (string[]),
typeof (MainWindowViewModel),
new PropertyMetadata(default(string[])));
public static readonly DependencyProperty SelectedItem1Property
= DependencyProperty.Register("SelectedItem1",
typeof (string),
typeof (MainWindowViewModel),
new PropertyMetadata(default(string)));
public string[] RBItems1
{
get { return (string[]) GetValue(RBItems1Property); }
set { SetValue(RBItems1Property, value); }
}
public string SelectedItem1
{
get { return (string)GetValue(SelectedItem1Property); }
set { SetValue(SelectedItem1Property, value); }
}
}
}
而 app.xaml 是:
<Application x:Class="RadioButtonListTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary Source="Themes\ShinyBlue\Theme.xaml"/>
</Application.Resources>
</Application>
【问题讨论】:
-
这是完全错误的 MVVM 方法,你是从 DependencyObject 继承 VM。您应该改为创建 UserControl。
标签: c# wpf mvvm radio-button themes