2012-08-26 5 views
1

4x LineSeries 차트가 있습니다. 선을 나타 내기 위해 두 가지 스타일을 정의했으며, 특정 LineSeries에 적용된 스타일을 동적으로 변경할 수 있기를 원합니다 (예 : 사용자가 버튼을 탭하는 등).C#으로 요소의 스타일을 동적으로 변경합니다.

C#에서 스타일을 업데이트하는 방법을 알아낼 수 없습니다. 어떤 도움을 주셔서 감사합니다!

lineChartMood.PolylineStyle = this.Resources.PolylineStyle2 as Style; 

하지만이 널 예외를 반환

이 나는 ​​노력했다. 여기

는 스타일 정의를 포함하여 페이지의 XAML입니다 :

<phone:PhoneApplicationPage 
    x:Class="Bhutaan.ChartingTest" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" 
    xmlns:local="clr-namespace:Bhutaan" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    SupportedOrientations="Portrait" Orientation="Portrait" 
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480" 
    shell:SystemTray.IsVisible="True"> 

    <phone:PhoneApplicationPage.Resources> 
     <Style x:Key="PolylineStyle" TargetType="Polyline"> 
      <Setter Property="StrokeThickness" Value="5"/> 
     </Style> 
     <Style x:Key="PolylineStyle2" TargetType="Polyline"> 
      <Setter Property="StrokeThickness" Value="1"/> 
     </Style> 
    </phone:PhoneApplicationPage.Resources> 


    <!--LayoutRoot is the root grid where all page content is placed--> 
    <Grid x:Name="LayoutRoot" Background="Transparent"> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="*"/> 
     </Grid.RowDefinitions> 

     <!--TitlePanel contains the name of the application and page title--> 
     <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 
      <TextBlock x:Name="ApplicationTitle" Text="TEST" Style="{StaticResource PhoneTextNormalStyle}"/> 
      <TextBlock x:Name="PageTitle" Text="added" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> 
     </StackPanel> 

     <!--ContentPanel - place additional content here--> 
     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,-0,12,0"> 
      <ScrollViewer> 
       <StackPanel> 
        <TextBlock Text="Great! That's been saved." FontSize="30" Margin="0,0,0,0"/> 
        <!-- Chart --> 
        <charting:Chart 
         x:Name="myChart" 
         Margin="0,20,0,0" 
         Height="350" 
         Style="{StaticResource PhoneChartStyle}" 
         Template="{StaticResource PhoneChartPortraitTemplate}"> 

         <!-- Series --> 
         <charting:LineSeries 
          x:Name="lineChartMood" 
          Title="Mood" 
          ItemsSource="{Binding}" 
          DependentValuePath="MoodValue" 
          IndependentValuePath="Timestamp" 
          PolylineStyle="{StaticResource PolylineStyle}" > 

          <charting:LineSeries.LegendItemStyle> 
           <Style TargetType="charting:LegendItem"> 
            <Setter Property="Margin" Value="5 0 5 0"/> 
           </Style> 
          </charting:LineSeries.LegendItemStyle> 
         </charting:LineSeries> 
         <!-- Series --> 
         <charting:LineSeries 
          Title="Energy" 
          ItemsSource="{Binding}" 
          DependentValuePath="EnergyValue" 
          IndependentValuePath="Timestamp"> 
          <charting:LineSeries.LegendItemStyle> 
           <Style TargetType="charting:LegendItem"> 
            <Setter Property="Margin" Value="5 0 5 0"/> 
           </Style> 
          </charting:LineSeries.LegendItemStyle> 
         </charting:LineSeries> 
         <!-- Series --> 
         <charting:LineSeries 
          Title="Mental" 
          ItemsSource="{Binding}" 
          DependentValuePath="MentalValue" 
          IndependentValuePath="Timestamp"> 
          <charting:LineSeries.LegendItemStyle> 
           <Style TargetType="charting:LegendItem"> 
            <Setter Property="Margin" Value="5 0 5 0"/> 
           </Style> 
          </charting:LineSeries.LegendItemStyle> 
         </charting:LineSeries> 
         <!-- Series --> 
         <charting:LineSeries 
          Title="Hunger" 
          ItemsSource="{Binding}" 
          DependentValuePath="HungerValue" 
          IndependentValuePath="Timestamp"> 
          <charting:LineSeries.LegendItemStyle> 
           <Style TargetType="charting:LegendItem"> 
            <Setter Property="Margin" Value="5 0 5 0"/> 
           </Style> 
          </charting:LineSeries.LegendItemStyle> 
         </charting:LineSeries> 
        </charting:Chart> 

       </StackPanel> 
      </ScrollViewer> 
     </Grid> 
    </Grid> 


</phone:PhoneApplicationPage> 
+0

위의 권한 부여 라인에서 nullpointerexception을 받는다고 가정합니다. 어떤 객체가 null인가? lineChartMood가 될 수 있습니까, 아니면 "PolylineStyle2"가 잘못 작성 되었습니까? 어떤 객체가 null인지 더 자세히 알 수 있습니까? 또한 C# 코드가 XAML 코드 숨김 위에 있습니까? –

+0

추가 디버깅은 style 요소가 null이 아니라는 것을 나타냅니다 ... null 인 lineChartMood 객체입니다. 왜 그럴 수 있죠? 코드 편집기에서 오류가 발생하지 않습니다 ...하지만 런타임에 null 인 것으로 보입니다 ... –

+0

정확하게 말하면 : 아래 답변에서 피드백을 기반으로 : lineChartMood.PolylineStyle = 스타일로 App.Current.Resources [ "PolylineStyle2"]; –

답변

5

코드를 테스트 한 결과 문제의 원인을 발견했습니다.

알 수없는 이유로 응용 프로그램에서 this.lineChartMood 필드를 설정하지 않았으므로 NullReferenceException이 발생합니다.

혼자서이 라인 시리즈 객체를 얻어야합니다. 이 그것을 얻을 수있는 두 가지 방법은 다음과 같습니다

var lineSeriesWay1 = this.FindName("lineChartMood"); 
var lineSeriesWay2 = myChart.Series.OfType<LineSeries>().First(ls => ls.Name == "lineChartMood"); 

는하지만 다음과 같이 생성자에 명시 적으로 필드 this.lineSeriesMood를 설정하는 것이 좋습니다 :

public partial class MainPage : PhoneApplicationPage 
{ 
    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
     // because the code 'this.FindName("lineChartMood")' doesn't work in the constructor, I'll use the following line: 
     this.lineChartMood = this.myChart.Series.OfType<LineSeries>().First(ls => ls.Name == "lineChartMood"); 

     // other code 
    } 


    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     this.lineChartMood.PolylineStyle = (Style)this.Resources["PolylineStyle2"]; 
     this.lineChartMood.Refresh(); // you should call this method so that the style is applied 
    } 
} 

그런 다음 당신은 당신의 시리즈에 참조 할 수있을 것이다 예외없이.

+0

@vortex 생성자의 멋진 체조 : p (+1 표) –

+0

감사합니다. 이제 예외없이 코드를 실행할 수 있습니다. 완전한! (후속 문제가 생겼습니다 ... 어떤 이유로 polyLineThickness 속성의 값을 줄일 수 있습니다 ... 증가시키지 않습니다. 즉, 5로 설정하면 변경할 수 있습니다. 런타임에 1,하지만 그 반대는 작동하지 않습니다). 답변을 주셔서 다시 한 번 감사드립니다. 죄송합니다. 답변을 수락하고 회신 해 주셔서 너무 오랜 시간이 걸렸습니다 (지난 몇 주 동안 직장을 다녀 왔습니다). 건배! –

2

lineChartMood.PolylineStyle = this.Resources.PolylineStyle2 as Style;lineChartMood.PolylineStyle = this.Resources["PolylineStyle2"] as Style;을해야을 ??

+0

그냥 ... 내가 NullReferenceException이를 얻을 ... –

+0

당신이 app.xaml에서 스타일을 정의하고 "application.current.resources ["PolylineStyle2 "]"를 통해 액세스를 시도 난 당신이하지 생각 리소스를 가져 오려고 할 때 같은 페이지에 있습니까? – TheHe

+0

확실히 시도한 ... 스타일 자체가 null로 돌아 오지 않습니다, lineChartMood 개체입니다. 어떤 이유로 그것은 런타임에 null입니다 ... 이유를 알아낼 수 없지만 위의 Gros Lalo는 내가 사용하고있는 차트 라이브러리의 버그 일 수 있다고 생각합니다 ... –

3

App.xaml에서 리소스를 추가하고 App.Current.Resources를 사용하여 리소스를 참조하는 것이 좋습니다. ?? 나는 프로그램이 특정 페이지에 정의 된 로컬 리소스를 참조 할 수 없을 수도 있다고 생각하기 때문에 이것을 말하고있다. 내가 틀렸을지도 모른다. 이것은 해결 방법이 아닙니다.

+0

방금 ​​시도해 봤는데 .. 여전히 동일한 Null 참조 예외가 발생합니다 ... 나는 여기에 뭔가 어리석은 일을해야합니다! –

관련 문제