如何从MVVM视图模型访问x:Name

时间:2019-05-16 05:14:06

标签: xaml mvvm xamarin.forms prism

我想从Viewmodel绑定Microchart数据以在我的xamarin棱镜应用程序中查看

我尝试通过访问x:Name及其正常工作来从后端c#进行绑定。但是我想将所有逻辑保留在viewmodel中。是否有任何方法可以从viewmodel访问此图表元素。

我的xaml代码

<StackLayout Orientation="Vertical" >
                    <StackLayout Padding="5,3,5,3" >

                        <microcharts:ChartView HeightRequest="300" WidthRequest="200" x:Name="chartView"/>
                    </StackLayout>
                    <StackLayout Padding="5,3,5,3" >

                        <microcharts:ChartView HeightRequest="300" WidthRequest="200" x:Name="chartView1"/>
                    </StackLayout>
                    <StackLayout Padding="5,3,5,3">

                        <microcharts:ChartView HeightRequest="300" WidthRequest="200" x:Name="chartView2"/>
                    </StackLayout>
                </StackLayout>

和我的后端C#代码

var entries = new List<ChartEntry>
                        {
                            new ChartEntry(200)
                            {
                                Label = "January",
                                ValueLabel = "200",
                                Color = SKColor.Parse("#266489")
                            },
                            new ChartEntry(400)
                            {
                                Label = "February",
                                ValueLabel = "400",
                                Color = SKColor.Parse("#68B9C0")
                            },
                            new ChartEntry(100)
                            {
                                Label = "March",
                                ValueLabel = "100",
                                Color = SKColor.Parse("#90D585")
                            }
                        };
            var chart = new BarChart() { Entries = entries };
            var chart1 = new BarChart() { Entries = entries };
            var chart2 = new PointChart() { Entries = entries };
            // or: var chart = new LineChart() { Entries = entries };
            // or: var chart = new DonutChart() { Entries = entries };
            // or: var chart = new RadialGaugeChart() { Entries = entries };
            // or: var chart = new RadarChart() { Entries = entries };
            this.chartView.Chart = chart;
            this.chartView1.Chart = chart1;
            this.chartView2.Chart = chart2;

我想将此后端C#代码移至viewmodel。而且我不知道如何将此图表数据绑定到viewmodel。谢谢

1 个答案:

答案 0 :(得分:0)

您不能这样做。

您可以使用BindingContext访问xml端。

  <microcharts:ChartView HeightRequest="300" WidthRequest="200" ValueLabel="{Binding your_prop}" x:Name="chartView"/>