通过XmlDataProvider将绑定复选框“IsChecked”值绑定到外部XML文件(利用MVVM)

时间:2014-02-18 20:20:10

标签: c# xml wpf data-binding xmldataprovider

在上周搜索并尝试了几个选项后,我似乎无法找到我要找的东西;也许有人可以提供帮助。在阅读本文时,请记住我尽可能严格地使用MVVM,尽管我对WPF相对较新。作为旁注,我使用Mahapps.Metro来设置窗口和控件的样式,找到了here

我有一个我的应用程序用于配置的XML文件(我无法使用app.config文件,因为应用程序无法安装在用户的系统上)。应用程序将在启动时查找此文件,如果找不到该文件,则会创建该文件。以下是XML的摘录:

<?xml version="1.0" encoding="utf-8"?>
<prefRoot>
  <tabReport>
    <cbCritical>True</cbCritical>
  </tabReport>
</prefRoot>

我在Window.Resources

中引用了XML文件
<Controls:MetroWindow.Resources>
        <XmlDataProvider x:Key="XmlConfig"
                         Source="%appdata%\Vulnerator\Vulnerator_Config.xml"
                         XPath="prefRoot"
                         IsAsynchronous="False"
                         IsInitialLoadEnabled="True"/>
</Controls:MetroWindow.Resources>

并将其用作DataContext的{​​{1}}:

MainWindow

接下来,我设置了一个“string-to-bool”转换器:

<Controls:MetroWindow DataContext="{DynamicResource XmlConfig}">

最后,我将class StringToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { bool? isChecked = (bool?)value; return isChecked; } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { string isChecked = value.ToString(); return isChecked; } return string.Empty; } } 绑定到相应的IsChecked

XPath

完成所有这些后,applciation会加载,但<Checkbox x:Name="cbCritical" Content="Critical" IsChecked="{Binding XPath=//tabReport/cbCritical, Converter={StaticResource StringToBool}}" /> 设置为IsChecked ...任何和所有想法都会对此有所帮助;提前谢谢!

1 个答案:

答案 0 :(得分:0)

我发现了问题...... XAML没有按预期处理文件路径中的%。为了更正,我从我的XAML XmlDataProvider声明中删除了以下内容:

Source="%appdata%\Vulnerator\Vulnerator_Config.xml" 
XPath="prefRoot" 

然后我在代码隐藏(.xaml.cs)中设置SourceXPath属性:

public MainWindow()
{
    InitializeComponent();

    Uri xmlPath = new Uri (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Vulnerator\Vulnerator_Config.xml");
    (this.Resources["XmlConfig"] as XmlDataProvider).Source = xmlPath;
    (this.Resources["XmlConfig"] as XmlDataProvider).XPath = "prefRoot";
}

现在,当应用程序加载时,复选框将设置为指定的XML节点的内部值。另外,我将Binding Mode=TwoWay设置为OneTime;双向绑定到XmlDataProvider不会按预期方式发生。为了解决这个问题,我将命令绑定到Checkbox,以使用新的Dictionary<string, string>值更新IsChecked(在我的视图模型构造函数中启动时创建)。我将使用Dictionary来控制应用程序根据用户输入执行的操作,并在应用程序关闭后将新的Dictionary用户值写入XML文件。