开发者

WPF bind to a static double var

开发者 https://www.devze.com 2022-12-28 10:48 出处:网络
i have these double values: public partial class Window1 : Window { public Window1() { InitializeComponent();

i have these double values:

 public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            double num1 = 50.0;
            double num2 = 90.0;
            double num3 = 120.0;
            double num4 = 20.0;
            double num5 = 80.0;

        }
    }

how do i bind them to xaml?

<vc:Chart.Series>
                <vc:DataSeries RenderAs="Column" AxisYType="Primary" >
                    <vc:DataSeries.DataPoints>
    开发者_如何学Python                    <vc:DataPoint AxisXLabel="Wall-Mart" YValue="{Binding Source={StaticResource num1}}" />

....

help please


Well, to make your XAML work as is you can store them in the resource dictionary like so:

public Window1()
{
    InitializeComponent();
    // don't actually do this
    this.Resources["num1"] = 50.0;
    this.Resources["num2"] = 90.0;
    this.Resources["num3"] = 120.0;
    this.Resources["num4"] = 20.0;
    this.Resources["num5"] = 80.0;
}

But that's not how you'd generally do it. Instead you should bind to a collection. Something like the following would be more useful.

public Window1()
{
    InitializeComponent();
    myDataSeries.ItemsSource = new double[] {50.0,90.0,120.0,20.0,80.0};
}

I don't really know the API for the chart control you're using but this is a commonly used pattern in WPF to have an ItemsSource property that can bind to a collection of values.


you can declare 'em in XAML, too.....

<Application
    xmlns:clr="clr-namespace:System;assembly=mscorlib">
    <Application.Resources>
          <clr:Double x:Key="num1">50.0</clr:Double>
          <clr:Double x:Key="num2">90.0</clr:Double>
          <clr:Double x:Key="num3">120.0</clr:Double>
          <clr:Double x:Key="num4">20.0</clr:Double>
          <clr:Double x:Key="num5">80.0</clr:Double>
    </Application.Resources>
</Application>

then, if you need to access via code....

if (Application.Current.Resources.Contains("num1"))
{
    (double)Application.Current.Resources["num1"];
}


You can't. They are variables with scope local to window constructor. You might want to turn them into public static fields like this:

public static readonly double Num1 = 50.0;

... and then reference them in XAML using {x:Static} markup extension like so:

<vc:DataPoint AxisXLabel="Wall-Mart" YValue="{x:Static local:Window1.Num1}" />

Alternatively, you may want to turn them into properties if they are meant to be changed like:

public double Num1 { get; set; }

<vc:DataPoint AxisXLabel="Wall-Mart" YValue="{Binding Num1,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}" />

Ultimately, you may make them a DependencyProperty if changes are to be automatically detected by XAML UI.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号