More specifically, how did the Duchy of Brandenburg inherit lands once held by a theocratic order?
In 1511, Albert, a member of the Brandenburg-Ansbach branch of the House of Hohenzollern was elected as the next Grand Master of the Teutonic Order after the death of Frederick of Saxony. His election was helped because of his relationship to his uncle Sigismund the Old, King of Poland and Grand Duke of Lithuania, whose Kingdom had been having disputes with the Teutonic Order regarding the Second Peace of Thorn.
However, when Albert came to power he refused to submit to his uncle and the Crown of Poland and reaffirmed his allegiance with the Pope and the Holy Roman Emperor. Albert tried to secure a string of alliances and in 1512 Muscovy invaded Lithuania, and the Teutonic Order refused the call to arms, and later formed an alliance with Vasilli III of Musocy, enraging Sigismund. Albert, feeling strengthened by his new allies demanded that Sigismund return all the territories taken under the terms of the Second Peace of Thorn, Sigismund declined and this led to the Polish-Teutonic War of 1519-1521. The war was indecisive and an armistice was called on April 5, 1521 due to the Ottoman invasion of Hungary.
In the four-year armistice Albert met Martin Luther and was convinced to abandon his Order, marry, and to convert Prussia into a hereditary duchy for himself. Albert agreed and in 1525 he converted to Lutheranism and was proclaimed as the Duke of Prussia in the Prussian Homage, by none other than Sigismund the Old, his new liege .
Duke Albert's son, Albert Frederick succeeded him as Duke, however due to an apparent mental disorder his cousin, George Frederick became his regent. On George's death in 1603, the Prince-Elector of Brandenburg and member of House Hohenzollern assumed the regency on the behest of Sigismund III Vasa of Poland. His son, John Sigismund succeed both himself and Albert Frederick on their respective deaths, becoming Prince-Elector of Brandenburg and Duke of Prussia.
This union of House Hohenzollern was known as Brandenburg-Prussia and continued until 1701 when John Sigismund's grandson, the then Duke Frederick III of Brandenburg-Prussia was proclaimed as Frederick I, King in Prussia [fixed, thanks Duzukian]. To achieve this Frederick persuaded Leopold I, Holy Roman Emperor and Archduke of Austria to name him King in exchange for an alliance against King Louis XIV in the War of the Spanish Succession.
TL:DR
Grand Master of Order converts to Lutheranism and makes himself Duke of Prussia. His son has a mental disorder and is succeed by his regent's son who is also a relative and member of House Hohenzollern. This new union then becomes a Kingdom in the early 18th century.