通过扩展Silverlight的控件DataGrid,使其垂直滚动条支持鼠标滑轮 (转)
时间:2011-01-19 来源:slwf7man
以下是扩展的方法
创建 Silverlight 工程
使用 Visual Studio 2008 and 创建一个新的 Silverlight 3 工程. 命名为 MouseScroll.
在Silverlight工程中新增一个类,命名为ScrollDataGrid.cs,让这个类继承SL3的DataGrid,代码如下
public class ScollDataGrid: DataGrid
{
}
你必须在程序中添加下面三个DLL
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Automation;
下面的方法就是实现DataGrid支持鼠标滑轮的方法
protected override void OnMouseWheel(MouseWheelEventArgs e)
{
base.OnMouseWheel(e);
//从datagrid取得AutomationPeer
AutomationPeer automationPeer = FrameworkElementAutomationPeer.FromElement(this);
if (automationPeer == null)
{
automationPeer = FrameworkElementAutomationPeer.CreatePeerForElement(this);
}
//得到 datagrid的scroll provider
IScrollProvider scrollProvider = automationPeer.GetPattern(PatternInterface.Scroll) as IScrollProvider;
if (scrollProvider != null)
{
ScrollAmount scrollAmount = ScrollAmount.NoAmount;
if (e.Delta < 0)
scrollAmount = ScrollAmount.SmallIncrement;//向下滑动
else if (e.Delta > 0)
scrollAmount = ScrollAmount.SmallDecrement;//向上滑动
if (scrollProvider.VerticallyScrollable)
{
scrollProvider.Scroll(ScrollAmount.NoAmount, scrollAmount);
}
}
}
在MainPage.xaml 新增如下命名空间:
xmlns:local="clr-namespace:MouseScroll"
然后再新增如下代码
<local:ScollDataGrid x:Name="myDataGrid" Height="100" HorizontalAlignment="Left" VerticalAlignment="Top" Width="271" Margin="20,20,0,0" />
现在我们新增一个类,然后向集合中新增一些数据来填充DataGrid
class PersonalData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public partial class MainPage : UserControl
{
List<PersonalData> myList;
public MainPage()
{
InitializeComponent();
#region Dummy List
myList = new List<PersonalData>
{
new PersonalData{ FirstName="FirstName1", LastName="LastName1", Age=39},
new PersonalData{ FirstName="FirstName2", LastName="LastName2", Age=40},
new PersonalData{ FirstName="FirstName3", LastName="LastName3", Age=41},
new PersonalData{ FirstName="FirstName4", LastName="LastName4", Age=42},
new PersonalData{ FirstName="FirstName5", LastName="LastName5", Age=43},
new PersonalData{ FirstName="FirstName6", LastName="LastName6", Age=44},
new PersonalData{ FirstName="FirstName7", LastName="LastName7", Age=45},
new PersonalData{ FirstName="FirstName8", LastName="LastName8", Age=46},
new PersonalData{ FirstName="FirstName9", LastName="LastName9", Age=47},
new PersonalData{ FirstName="FirstName10", LastName="LastName10", Age=48},
new PersonalData{ FirstName="FirstName11", LastName="LastName11", Age=49},
new PersonalData{ FirstName="FirstName12", LastName="LastName12", Age=50},
new PersonalData{ FirstName="FirstName13", LastName="LastName13", Age=51},
new PersonalData{ FirstName="FirstName14", LastName="LastName14", Age=52},
};
#endregion
myDataGrid.ItemsSource = myList;
}
}
现在运行程序,那么垂直滚动条就可以用鼠标滑轮滑动了
希望以上代码对大家有帮助,大家也可以根据此代码来扩展ListBox,TreeView。其中第三方控件已经修补这个BUG
另外,如果大家觉得有用,就支持一下,谢谢