如何在WPF中使用Slider设置Grid的字体大小

时间:2013-10-24 15:18:50

标签: c# .net wpf

我创建了WPF项目。在这里我使用了GridControl和Slider!我使用了滑块值来通过BindingINotifyProperty更改GridControl的FontSize。问题是它更改了FontSize的值,但它不适用并生成Null Object Reference Error at:

CS文件:

private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            // ... Get Slider reference.
            var slider = sender as Slider;
            // ... Get Value.
            double value = slider.Value;
            // ... Set Window Title.
            this.grid.FontSize = value;   // Error HERE
        }

XAML CODE

 <Grid>
           <Slider Minimum="15" Maximum="30" Value="{Binding GridFontSize, Mode=TwoWay}" ValueChanged="Slider_ValueChanged" />

           <dxg:GridControl AutoGenerateColumns="AddNew" Name="grid"  Margin="0,25,0,0">
            <dxg:GridControl.View>
                         <dxg:TableView Name="View" AllowEditing="False" ShowTotalSummary="True" PreviewMouseDown="View_PreviewMouseDown" MouseDown="View_MouseDown"  />
               </dxg:GridControl.View>
            </dxg:GridControl>
    </Grid>

如何解决这个问题?任何人都可以回答我的问题吗?

2 个答案:

答案 0 :(得分:1)

首先使用Grid属性为您的Name命名:

<Grid Name="YourGrid">
    <Slider Minimum="15" Maximum="30" Value="{Binding GridFontSize, Mode=TwoWay}" 
        ValueChanged="Slider_ValueChanged" />
        <dxg:GridControl AutoGenerateColumns="AddNew" Name="grid"  Margin="0,25,0,0">
        <dxg:GridControl.View>
            <dxg:TableView Name="View" AllowEditing="False" ShowTotalSummary="True" 
                PreviewMouseDown="View_PreviewMouseDown" MouseDown="View_MouseDown" />
        </dxg:GridControl.View>
    </dxg:GridControl>
</Grid>

现在,您可以使用该名称在代码中引用它:

private void Slider_ValueChanged(object sender, 
    RoutedPropertyChangedEventArgs<double> e)
{
    // ... Get Slider reference.
    var slider = sender as Slider;
    // ... Get Value.
    double value = slider.Value;
    // ... Set Window Title.
    TextElement.SetFontSize(YourGrid, value);
}

答案 1 :(得分:0)

存在无效值,因此您需要将代码放入try catch中。在catch中将其设置为零。还要检查零以下的值并设置为零。

我有类似的代码,其中字体大小也绑定到滑块,并在下面的fontsize上有一个转换器:

public class IntToDoubleConverter:IValueConverter {

public object Convert( object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
    double result = 0;

    try
    {
        result = (double)((int)value);


    }
    catch (Exception) { }

    return result;
}

public object ConvertBack( object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
    return (int) ((double)value);
}

}