在执行XamlReader.Load之后,绑定ComboBox.ItemsSource w/绑定SelectedValue的奇怪问题. [英] Strange problem binding ComboBox.ItemsSource w/ bound SelectedValue after doing XamlReader.Load.

查看:49
本文介绍了在执行XamlReader.Load之后,绑定ComboBox.ItemsSource w/绑定SelectedValue的奇怪问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建的应用程序中遇到了一个奇怪的问题.我创建了一个小样本来演示此问题.这是示例项目的URL:

http://www.mediafire.com /file/jidnurm5ozd/ProblemWithBindingAfterXamlRead.zip

在示例应用程序中,我有一个名为"FoodData"的类.该类具有一个名为FoodCode的DependencyProperty.我在主窗口中创建一个实例,然后将Foodcode设置为"TOM". (这是西红柿"的食物代码).

主窗口允许您启动子对话框.这就是问题所在.我将FoodData实例传递给其构造函数中的子对话框,并将该子对话框的DataContext设置为该对象.子对话框有一个控件,该控件的控件模板已设置. ControlTemplate具有一个ComboBox,可将SelectedValue绑定到传入的FodData对象.那个ComboBox看起来像这样:

I've encountered a strange problem in an application that I'm creating.  I have created a small sample demonstrating this problem.  Here is the URL to the sample project:

http://www.mediafire.com/file/jidnurm5ozd/ProblemWithBindingAfterXamlRead.zip

In my sample app, I have a class named "FoodData".  That class has a DependencyProperty called FoodCode.  I create an instance of one of those in the main window, and set Foodcode to "TOM" (which is the food code for "tomato").

The main window allows you to launch a subdialog.  That's where the problem comes in.  I pass the FoodData instance to the subdialog in its constructor, and set the subdialog's DataContext to that object.  Subdialog has a Control whose ControlTemplate is being set.  The ControlTemplate has a ComboBox that binds SelectedValue to the FodData object that was passed in.  That ComboBox looks like this:

<ComboBox HorizontalAlignment="Left" Width="200" x:Name="foodCombo"
      ItemsSource="{Binding Source={x:Static local:FoodLists.Foods}}"
      SelectedValuePath="Code"
      DisplayMemberPath="Description"
      SelectedValue="{Binding FoodCode}" />



FoodList.Foods(组合框的ItemsSource)是FoodSpecifier对象的列表.每个都有一个说明和一个代码:



FoodList.Foods (the ItemsSource for the ComboBox) is a list of FoodSpecifier objects.  Each one has a Description and a Code:

s_foods = new List<FoodSpecifier>();
s_foods.Add(new FoodSpecifier { Description = "corn", Code = "COR" });
s_foods.Add(new FoodSpecifier { Description = "pepper", Code = "PEP" });
s_foods.Add(new FoodSpecifier { Description = "onion", Code = "ONI" });
s_foods.Add(new FoodSpecifier { Description = "tomato", Code = "TOM" });
s_foods.Add(new FoodSpecifier { Description = "zuccini", Code = "ZUC" });
s_foods.Add(new FoodSpecifier { Description = "mushroom", Code = "MUS" });


该子对话框仅适用于该代码.当我调出子对话框时,ComboBox正确显示西红柿",因为FoodData.FoodCode是"TOM".并且SelectedValuePath是代码"但是,如果我添加了在App.cs中读取的Xaml,则子对话框会出现问题:


The subdialog works fine with just that code.  When I bring up the subdialog, the ComboBox correctly shows "tomato", since the FoodData.FoodCode is "TOM" and the SelectedValuePath is "Code" on the ComboBox.

The subdialog has problems, though, if I add in a Xaml read in App.cs:

protected override void OnStartup(StartupEventArgs e) {
    base.OnStartup(e);
    string xaml = xamlStrings[0];
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(xaml);
    MemoryStream stream = new MemoryStream(bytes);
    if (MessageBoxResult.Yes == MessageBox.Show("Call XamlReader.Load?", "Test", MessageBoxButton.YesNo))
        XamlReader.Load(stream);
}


当包含该代码时,子对话框在第一次启动时起作用.但是,每次以后我启动它时,ComboBox都保持空白. 番茄"未选中.如果我在ComboBox上获得了SelectedValue的BindingExpression,并调用BindingExpression.UpdateTarget,则ComboBox会正确地选择"tomato".值.

我使用XamlReader读取的特定Xaml也很重要.我正在使用一个Setter加载样式.我已经试验了不同的属性,到目前为止,我可以说这些属性将导致这种行为表现出来:

-ScrollViewer.Horizo​​ntalScrollBarVisibility(设置为Auto)
-ScrollViewer.VerticalScrollBarVisibility(设置为Auto)
-ScrollViewer.CanContentScroll(设置为false)

并且以下属性不会导致该行为表现出来:

-Grid.Row(设置为0)
-TextElement.FontSize(设置为12)
-模板(设置为null)
-DockPanel.Dock(设置为顶部)

I意识到这似乎是一个奇怪的事件序列,但是所有这些事情都必须在我的完整应用程序中进行.我尽可能精简了此样本,但仍然会重现该问题.

在此先感谢您抽出宝贵时间来解决这个问题. :-)

David


When that code is included, the subdialog works the first time it is brought up.  Every subsequent time I launch it, though, the ComboBox stays blank; "tomato" isn't selected.  If I get the BindingExpression for SelectedValue on the ComboBox, and call BindingExpression.UpdateTarget, the ComboBox then correctly selects the "tomato" value.

The particular Xaml that I read using XamlReader matters as well.  I am loading a Style with a single Setter.  I've experimented with different properties, and so far I can say that these properties will cause this behavior to manifest:

- ScrollViewer.HorizontalScrollBarVisibility (set to Auto)
- ScrollViewer.VerticalScrollBarVisibility (set to Auto)
- ScrollViewer.CanContentScroll (set to false)

And the following properties will not cause the behavior to manifest:

- Grid.Row (set to 0)
- TextElement.FontSize (set to 12)
- Template (set to null)
- DockPanel.Dock (set to Top)

I realize this seems like an odd sequence of events, but those are all things that have to happen in my full app.  This sample is as stripped down as I could make it and still reproduce the problem.

Thanks in advance for anyone that takes the time to wade through this. :-)

David

推荐答案

大卫,您好,

我运行您的示例项目并完成了看到我这边的问题.

起初,我认为应用程序启动时解析的样式已应用于子对话框中的Control.然后,我注意到您没有将解析的样式添加到应用程序的资源"部分,也没有将此样式设置为子对话框中控件"的样式"属性.

我尝试将样式手动添加到应用程序的资源"部分,并且在应用程序启动时不调用XamlReader.Load方法.在这种情况下,问题消失了.

App.xaml

<应用程序x:Class ="ProblemWithBindingAfterXamlRead.App"
    xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation " ;
    xmlns:x =" http://schemas.microsoft.com/winfx/2006/xaml "
    StartupUri ="Main.xaml">
    < Application.Resources>
       < Style TargetType =控件">
            < Setter Property =" ScrollViewer.Horizo​​ntalScrollBarVisibility"值=自动"/<            < Setter Property =" ScrollViewer.VerticalScrollBarVisibility"值=自动". />
           < Setter Property =" ScrollViewer.CanContentScroll"值="false"/>
           < Setter Property =" TextElement.FontSize"值="12"/<            < Setter Property =模板";值="{x:Null}" />
           < Setter Property ="DockPanel.Dock";值=最高". />
       </Style>
</Application.Resources>
</Application>

然后我尝试在代码中向应用程序的Resouces部分添加样式,但是问题再次出现. />
App.xaml.cs

  公共局部类应用程序:应用程序{
   
        静态字符串xamlStrings =< Style xmlns = \"" http://schemas.microsoft.com/winfx /2006/xaml/presentation \ " " +
           " xmlns:x = \" http://schemas.microsoft.com/winfx/2006/xaml\ TargetType =控制". +
           << Setter Property = \" ScrollViewer.Horizo​​ntalScrollBarVisibility \"值= \自动" />" +
           < Setter Property = \" ScrollViewer.VerticalScrollBarVisibility \"值= \自动" />" +
           << Setter Property = \" ScrollViewer.CanContentScroll \"值= \"false \" />" +        
           < Setter Property = \" Background \"值= \"red \" />" +
          << Setter Property = \" TextElement.FontSize \"值= \"12" />" +
          < Setter Property = \" Template \"值= \" {x:Null} \" />" +
          < Setter Property = \" DockPanel.Dock \"值= \"Top \" /></Style>;
      

Hi David,

I run your sample project and did see the problem on my side.

At first, I thought the style parsed when the application is started was applied to the Control in the subdialog. Then I noticed that you didn't either add the parsed style to the Resources section of the application, or set this style to the Style property of the Control in the subdialog.

I have tried adding the style to the Resources section of the application manually and don't call the XamlReader.Load method when the application is started. In this case, the problem disappeared.

App.xaml

<Application x:Class="ProblemWithBindingAfterXamlRead.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Main.xaml">
    <Application.Resources>
        <Style TargetType="Control">
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
            <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
            <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
            <Setter Property="TextElement.FontSize" Value="12"/>
            <Setter Property="Template" Value="{x:Null}" />
            <Setter Property="DockPanel.Dock" Value="Top" />
        </Style>
    </Application.Resources>
</Application>

Then I tried to add the style to the Resouces section of the application in code, but the problem appeared again.

App.xaml.cs

   public partial class App : Application {
     
        static string xamlStrings = "<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
            "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" TargetType=\"Control\">" +
            "<Setter Property=\"ScrollViewer.HorizontalScrollBarVisibility\" Value=\"Auto\" />" +
            "<Setter Property=\"ScrollViewer.VerticalScrollBarVisibility\" Value=\"Auto\" />" +
            "<Setter Property=\"ScrollViewer.CanContentScroll\" Value=\"false\" />" +         
            "<Setter Property=\"Background\" Value=\"red\" />" +
           "<Setter Property=\"TextElement.FontSize\" Value=\"12\" />" +
           "<Setter Property=\"Template\" Value=\"{x:Null}\" />" +
           "<Setter Property=\"DockPanel.Dock\" Value=\"Top\" /></Style>";
       

      公共静态样式ParseStyle(字符串文本)
{
                      字符串xaml =文本;

        public static Style ParseStyle(string text)
        {
            string xaml = text;

           byte [] bytes = System.Text.Encoding.ASCII.GetBytes(xaml);
MemoryStream流=新的MemoryStream(字节);

        返回样式;    &bb  
     }

        受保护的重写void OnStartup(StartupEventArgs e){
base.OnStartup(e);
此参数);
        }
我还没弄清楚为什么以编程方式将样式添加到应用程序的资源"部分时会出现问题,而在设计时添加样式时却不存在问题.

此致,
刘琳达

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(xaml);
            MemoryStream stream = new MemoryStream(bytes);
            Style style = XamlReader.Load(stream) as Style;
            return style;           
        }

        protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);
            this.Resources.Add(typeof(Control),ParseStyle(xamlStrings));
          }
     }

I haven't worked out why the problem exists when adding the style to the application's Resources section programmatically, while the problem doesn't exist when adding the style at design time.

Sincerely,
Linda Liu


这篇关于在执行XamlReader.Load之后,绑定ComboBox.ItemsSource w/绑定SelectedValue的奇怪问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆